2017-07-04 149 views
0

我開發簡單的REST API的應用程序,並嘗試使用本教程來測試它:http://memorynotfound.com/unit-test-spring-mvc-rest-service-junit-mockito/單元測試 - 投問題

我已經用我的工作REST API test_get_all_success單元測試來實現整個(寫在Spring MVC )。不幸的是,由於以下問題,測試無法運行。

這裏是整個測試文件:

import java.util.Arrays; 
import static org.mockito.Mockito.when; 
import static org.springframework.test.web.client.match.MockRestRequestMatchers.content; 
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; 

import org.junit.Test; 
import org.junit.runner.RunWith; 
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 static org.hamcrest.Matchers.*; 
import org.junit.Before; 
import org.mockito.InjectMocks; 
import org.mockito.Mock; 
import static org.mockito.Mockito.*; 
import org.mockito.MockitoAnnotations; 
import org.springframework.http.MediaType; 
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; 
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; 
import org.springframework.test.web.servlet.setup.MockMvcBuilders; 

@RunWith(SpringJUnit4ClassRunner.class) 
@ContextConfiguration(classes={MyConfigClass.class}) 
@WebAppConfiguration 
public class ClientTest { 

    private MockMvc mockMvc; 

    @Mock 
    private ClientManagerImpl clientManager; 

    @InjectMocks 
    private ClientController clientController; 

    @Before 
    public void init(){ 
     MockitoAnnotations.initMocks(this); 
     mockMvc = MockMvcBuilders 
       .standaloneSetup(clientController) 
       .build(); 
    } 

    @Test 
    public void findAll_ClientsFound_ShouldReturnFoundClients() throws Exception { 
     Client a = ...; 
     Client b = ...; 

     when(clientManager.getClients()).thenReturn(Arrays.asList(a, b)); 

     mockMvc.perform(get("/clients")) 
       .andExpect(status().isOk())    
     .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) 
       .andExpect(jsonPath("$", hasSize(2))); 

     verify(clientManager, times(1)).getClients(); 
     verifyNoMoreInteractions(clientManager); 
    } 

} 

NetBeans的顯示錯誤在這行:

.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) 

incompatible types: RequestMatcher cannot be converted to ResultMatcher 

測試不能因爲這個錯誤的運行。當我刪除這行時,一切正常,測試通過。

我在做什麼錯?

+0

我沒有看到您發佈的內容有任何問題。你能從你的測試方法發佈更多的代碼嗎? – Abubakkar

+0

謝謝你的回覆,代碼更新 –

回答

2

下面的靜態導入將導致衝突:

import static org.springframework.test.web.client.match.MockRestRequestMatchers.content; 

MockRestRequestMatchers類用於使用MockRestServiceServer客戶端的靜態測試,但你在這裏測試的MVC應用程序控制器。

+0

Thenk你很好,現在工作正常:) –