我想使用 Spring 测试框架
为 Restful Web 服务
编写一个测试用例。我模拟了该服务并能够成功运行测试用例。
但是,当服务被模拟时,它返回空响应。因此,我想设置服务的预期输出。
我可以使用不同的模拟框架来实现它,例如Mockito
或Jmockit
(在下面的代码中它是使用Mockito)。
但是,除了内部 Spring 测试框架
之外,是否可以无需任何添加/外部测试框架
。
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import java.util.Arrays;
import static org.hamcrest.Matchers.*;
import static org.hamcrest.Matchers.is;
import static org.mockito.Mockito.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.model;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {TestContext.class, WebAppContext.class})
@WebAppConfiguration
public class TodoControllerTest {
private MockMvc mockMvc;
@Autowired
private TodoService todoServiceMock;
@Test
public void findAll_ShouldAddTodoEntriesToModelAndRenderTodoListView() throws Exception {
Todo first = new TodoBuilder()
.id(2L)
.description("Lorem ipsum")
.title("Bar")
.build();
/**
Need mocking technique from Spring Testing Framework
*/
when(todoServiceMock.findAll()).thenReturn(Arrays.asList(first));
mockMvc.perform(get("/"))
.andExpect(status().isOk())
.andExpect(view().name("todo/list"))
.andExpect(forwardedUrl("/WEB-INF/jsp/todo/list.jsp"))
.andExpect(model().attribute("todos", hasSize(2)))
.andExpect(model().attribute("todos", hasItem(
allOf(
hasProperty("id", is(1L)),
hasProperty("description", is("Lorem ipsum")),
hasProperty("title", is("Foo"))
)
)))
.andExpect(model().attribute("todos", hasItem(
allOf(
hasProperty("id", is(2L)),
hasProperty("description", is("Lorem ipsum")),
hasProperty("title", is("Bar"))
)
)));
}
}
最佳答案
一种可能的解决方案是扩展您想要测试的类并覆盖您想要模拟的方法。然后在一个单独的配置文件中定义一个 bean,它将代替真实对象进行连接。接下来在您的测试类中使用此配置。
这实际上是 Mockito spy 的行为。如果我是你,我会坚持使用它,因为它提供了更大的灵 active 并节省了大量的样板代码。
关于java - 使用 Spring 测试框架模拟服务的预期结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25781866/