2016-08-18 9 views
1

私はSpring unit testingの新人です。 Spring restコントローラ用のテストケースの作成私はこのようにSpring Controller統合TestNgを使用したテスト

@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を初期化した場合、それは完璧に動作し、私のallTestケースはパスしている間:(理由を知りません失敗しました。スタンドアロンのコントローラを使用して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のセットアップ(最初のコードを参照)のほぼすべてのソリューションを試しました。これは、このWebサイトと主に春の公式サイトのWebサイトなどで、同じように見ています。 これを見てみましょう!乾杯!

+0

mockMvcを次のように変更してレスポンスを出力します:System.out.println(mockMvc.perform(get/"/ v1/testSessions/{testSessionId}/tasks"、1l))。getResponse()。getContentAsString()) ; – Journeycorner

+0

私たちの後にgetResponse()がありません。追加中にエラーが発生しました – shiva

+0

あなたは応答ステータスを取得しているので、応答本体もあるはずです。コントローラ内にブレークポイントを設定し、ヌル値を探します。また、TESTNGの代わりにJUnit(注釈)を使用することもできます。 – Journeycorner

答えて

0

すべての春と技術のことを忘れて、テストで何を成し遂げたいのですか?あなたが本当の統合テストを行いたい場合は

、モックではないコントローラまたはサービスを行うため、次のコードでは意味がありません:あなたのセットアップに問題があるべき

@Mock 
private TaskService taskServiceMock; 

を。 MockMvcの代わりにすべてのMockを削除して、やり直してください。コーヒーを飲んでofficial documentationを読むと、インメモリデータベースの設定やSpring TestContext Frameworkの設定など、すべての詳細が教えられます。

コントローラにアクセスするには、テストの深さに応じてtwo choicesが必要です。

+0

いいえ。私はあなたが誤解していると思います! 2番目のコードはユニットテスト用ですmockitoを使用してサービスクラスオブジェクトを嘲笑しています...それはうまくいきます。すべてのテストケースはスタンドアロンセットアップを使用して渡されます..エラーはありません!最初のコードでは、私は統合テストを行っています..コードのテストを終わらせて.... webapplicationcontextの設定を使用して、mockMvcを通してurlを呼び出している間にエラーが発生しています。それは内部サーバーのエラーを提供します。私はコントローラのオブジェクトを作成して同じメソッドを呼び出す場合、それは完璧に動作している.. ..そこにいくつかの問題はありますか?それを見てください – shiva

+0

もし私がapplicationContext.xmlのコードを追加することもできますが... @AutowiredプライベートTaskController taskControllerを使用してコントローラのインスタンスを作成した後、それはうまく動作するので、必要はないと思います。だからmockMvcと何か間違っている..私は、オブジェクトがmockmvcとwebapplicationContextで作成されているデバッグポイントを置くことでチェックしますが、私が得られなかったエラーは何ですか?私は助けが必要です! – shiva

+0

アプリケーションを手動で起動すると機能しますか?あなたの問題は、内部のサービスがautowiredにならないことは明らかです。ここで説明するように、 "@RunWith(SpringRunner.class)"を試してください:http://docs.spring.io/spring/docs/current/spring-framework-reference/html/integration-testing.html#spring-mvc-test-サーバ。それでも動作しない場合は、JUnitを使用してください。後で元に戻すことができます。エラーの原因ではないことを確認してください。 – Journeycorner

関連する問題