弹簧控制器集成测试使用TestNg



我是Spring单元测试的新手。为Spring rest控制器编写测试用例。当我以这种方式编写测试用例时

@WebAppConfiguration
@ContextConfiguration(locations = {"file:src/test/resources/applicationContext.xml"})
public class TaskControllerIntegrationTest extends AbstractTransactionalTestNGSpringContextTests {
    private MockMvc mockMvc;
    @Autowired
    private WebApplicationContext wac;
    @BeforeClass
    public void setUp() {
        this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
    }
    @Test
    public void testGetAllTasks() throws Exception {
        mockMvc.perform(get("/v1/testSessions/{testSessionId}/tasks", 1l))
                .andExpect(status().isOk());

    }
}

我得到测试用例失败不知道为什么:(而如果我使用独立控制器初始化MockMvc,它工作完美,我的所有测试用例都通过。使用独立控制器的MockMvc的设置是这样的。它用于单元测试:

@Mock
    private TaskService taskServiceMock;
    @InjectMocks
    private TaskController taskController;

    private MockMvc mockMvc;
    @Spy
    List<Task> allTasks = new ArrayList<Task>();
   /* @Spy
    List<TaskSessionModel> taskSessionModelList = new ArrayList<TaskSessionModel>();*/
    @BeforeClass
    public void setUp() {
        //    Mockito.reset(taskServiceMock);
        MockitoAnnotations.initMocks(this);
        //       taskSessionModelList = getAllTaskSessionModels();
        allTasks = getAllTasks();
        this.mockMvc = MockMvcBuilders.standaloneSetup(taskController).build();
    }
    @Test
    public void testGetAllTasks() throws Exception {
        //  when(taskSessionDao.findAllByTestSession(1l)).thenReturn(taskSessionModelList);
        when(taskServiceMock.getAllTasks(1l)).thenReturn(allTasks);
        mockMvc.perform(get("/v1/testSessions/{testSessionId}/tasks", 1l)
                .accept(MediaType.APPLICATION_JSON_VALUE))
                .andExpect(status().isOk())
                .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
                .andExpect(jsonPath("$", hasSize(2)))
                .andExpect(jsonPath("$[0].name", is("Average")));

        List<Task> expTaskList = taskController.getAllTasks(1l);
        verify(taskServiceMock, times(2)).getAllTasks(1l);
        verifyNoMoreInteractions(taskServiceMock);
        assertEquals(allTasks, expTaskList);
    }

但是如果我通过使用WebApplicationContext编写相同的单元测试…我将得到错误,测试用例将失败:

java.lang.AssertionError: Status 
Expected :200
Actual   :500
 <Click to see difference>

    at org.springframework.test.util.AssertionErrors.fail(AssertionErrors.java:60)
    at org.springframework.test.util.AssertionErrors.assertEquals(AssertionErrors.java:89)
    at org.springframework.test.web.servlet.result.StatusResultMatchers$10.match(StatusResultMatchers.java:654)
    at org.springframework.test.web.servlet.MockMvc$1.andExpect(MockMvc.java:152)
    at com.blueoptima.dt.controller.TaskControllerIntegrationTest.testGetAllTasks(TaskControllerIntegrationTest.java:46)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:84)
    at org.testng.internal.MethodInvocationHelper$1.runTestMethod(MethodInvocationHelper.java:200)
    at org.springframework.test.context.testng.AbstractTestNGSpringContextTests.run(AbstractTestNGSpringContextTests.java:171)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.testng.internal.MethodInvocationHelper.invokeHookable(MethodInvocationHelper.java:212)
    at org.testng.internal.Invoker.invokeMethod(Invoker.java:707)
    at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:901)
    at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1231)
    at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:127)
    at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:111)
    at org.testng.TestRunner.privateRun(TestRunner.java:767)
    at org.testng.TestRunner.run(TestRunner.java:617)
    at org.testng.SuiteRunner.runTest(SuiteRunner.java:334)
    at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:329)
    at org.testng.SuiteRunner.privateRun(SuiteRunner.java:291)
    at org.testng.SuiteRunner.run(SuiteRunner.java:240)
    at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
    at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)
    at org.testng.TestNG.runSuitesSequentially(TestNG.java:1224)
    at org.testng.TestNG.runSuitesLocally(TestNG.java:1149)
    at org.testng.TestNG.run(TestNG.java:1057)
    at org.testng.IDEARemoteTestNG.run(IDEARemoteTestNG.java:74)
    at org.testng.RemoteTestNGStarter.main(RemoteTestNGStarter.java:124)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)

我不知道怎么了?我尝试了几乎所有的解决方案的WebApplicationContext设置(见第一个代码),它是在相同的方式,我看到…在这个网站和大部分配置在春季官方网站和其他谷歌后,但仍然错误保持不变?看看这个吧!干杯! !

退回一步,忘记所有Spring和技术方面的东西,问问自己想通过测试实现什么?

如果你想做一个真正的集成测试,不要模拟控制器或服务,所以下面的代码没有意义:

@Mock
private TaskService taskServiceMock;

这应该是您的设置中的问题。删除所有mock而不是MockMvc,然后再试一次。喝杯咖啡,阅读官方文档,它会教你所有的细节,包括设置内存数据库和设置Spring TestContext框架。

要访问控制器,您有两种选择,这取决于测试的深度。

最新更新