【发布时间】:2017-07-04 13:47:54
【问题描述】:
我正在开发简单的 Rest API 应用程序并尝试使用本教程对其进行测试:http://memorynotfound.com/unit-test-spring-mvc-rest-service-junit-mockito/
我已经使用我工作的 Rest API(用 Spring MVC 编写)实现了整个 test_get_all_success 单元测试。不幸的是,由于以下问题,测试无法运行。
这是整个测试文件:
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
由于此错误,测试无法运行。当我删除此行时,一切正常,测试通过。
我做错了什么?
【问题讨论】:
-
我从您发布的内容中看不出任何问题。你能从你的测试方法中发布更多代码吗?
-
感谢回复,代码已更新
标签: java unit-testing spring-mvc junit mockito