2017-07-04 154 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你很好,现在工作正常:) –