0
我有RESTful服务,我想单元测试它们没有连接到数据库,所以我写了这段代码:为什么mockMVC和mockito不能一起工作?
@Before
public void setup() throws Exception {
this.mockMvc = webAppContextSetup(webApplicationContext).build();
adminDao = mock(AdminDaoImpl.class);
adminService = new AdminServiceImpl(adminDao);
}
@Test
public void getUserList_test() throws Exception {
User user = getTestUser();
List<User> expected = spy(Lists.newArrayList(user));
when(adminDao.selectUserList()).thenReturn(expected);
mockMvc.perform(get("/admin/user"))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$", hasSize(1)))
;
}
服务被调用,但我的问题是这行代码
when(adminDao.selectUserList()).thenReturn(expected);
不工作,我的意思是它真的调用了adminDao.select方法,因此从数据库中获取结果。我不想要。 你有什么想法如何嘲笑方法调用?
它们一起工作得非常好,但是你在模拟上下文之外的类,上下文应该如何知道这些模拟? –
@ M.Deinum你是对的,我知道我得到了webApplicationContext,但实际上我找不到在mockMVC上下文中模拟它们的方法。我该如何解决它? – Shilan
创建一个配置类,它使用mock覆盖实际的bean。在我们的测试课中注入模拟记录你想要的行为。 –