【发布时间】:2016-04-28 11:14:06
【问题描述】:
我有restful服务,我想在不连接数据库的情况下对它们进行单元测试,因此我写了这段代码:
@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 上下文中模拟它们的方法。我该如何解决?
-
创建一个配置类,用模拟覆盖实际的 bean。在我们的测试类中注入 mock 来记录你想要的行为。
-
所以你的意思是我需要创建一个像 @Configuration public class TestContext {} 这样的类,然后像这样注入它 @ContextConfiguration(classes = {TestContext.class, WebAppConfig.class}) 对不起只是想要以确保我得到你真正的意思。
-
也许这个答案可以解决你的问题:stackoverflow.com/a/16207069/887692
标签: spring junit mockito mockmvc