spring - 为什么mockMVC和mockito不能一起工作?

标签 spring junit mockito mockmvc

我有 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,我解决了我的问题,我添加了一个 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})

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

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

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

关于spring - 为什么mockMVC和mockito不能一起工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36912981/

相关文章:

java - Spring 4 中 ExpressionEvaluationUtils 的替代方案

java - 如何在 junit 测试我的类(class)时抛出 `InterruptedException`?

java - Spring boot @Autowired 无法初始化类

java - JUnit 和测试文件

java - 是什么导致了这个mockito异常?

java - stub 一个方法,但仍然检查它是否是使用mockito调用的

java - 使用 PowerMockito 1.6 验证静态方法调用

java - 运行时错误 PowerMock + Mockito : ProxyFrameworkImpl could not be located in classpath

spring - 在可分页资源上生成自链接时出错

eclipse - 在 eclipse 中设置 Spring 和 Tomcat?