【问题标题】:Why mockMVC and mockito don't work together?为什么 mockMVC 和 mockito 不能一起工作?
【发布时间】: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


【解决方案1】:

感谢@M。 Deinum,我解决了我的问题,我添加了一个 TestContext 配置文件:

@Configuration
public class TestContext {

@Bean
public AdminDaoImpl adminDao() {
    return Mockito.mock(AdminDaoImpl.class);
}

@Bean
public AdminServiceImpl adminService() {
    return new AdminServiceImpl(adminDao());
}       
}

然后在我的测试类中,我用

注释了该类
@ContextConfiguration(classes = {TestContext.class})

值得一提的是,在测试类的设置中我需要重置 mockedClass 以防止泄漏:

@Before
public void setup() throws Exception {
    Mockito.reset(adminDaoMock);

    mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
}

【讨论】:

【解决方案2】:

不要创建单独的 TestContext 类,而是使用 @MockBean 注解。

 @MockBean
 AdminDao 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)))
    ;           
}

【讨论】:

    猜你喜欢
    • 2020-12-31
    • 2020-03-04
    • 2016-01-04
    • 1970-01-01
    • 1970-01-01
    • 2020-05-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多