【问题标题】:Spring Boot, Mockito, injecting mock into scope session beanSpring Boot,Mockito,将模拟注入范围会话 bean
【发布时间】:2018-08-31 07:01:51
【问题描述】:

我在将模拟注入到我需要测试的一个类中时遇到问题。我正在尝试模拟一个 Dao 类,并且在我正在使用的各种服务中使用 ReflectionTestUtils 这样做没有问题,但是这个只是不想工作,它不断调用 Dao 类并从数据库中获取错误。

这是测试类:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
@WebAppConfiguration
public class DedicationControllerTest extends AbstractRestTest {

    @Mock
    UserDaoImpl userDao;

    @Autowired
    @InjectMocks
    GrantedAuthoritiesLevelsHolder grantedAuthoritiesLevelsHolder;

    @Test
    public void shouldTest() throws Exception {
        //given
        String json = this.getJsonFromFile("json/my.json");

        Mockito.when(userDao.getUser(Mockito.anyString())).thenReturn(new User(1l, "mock"));
        ReflectionTestUtils.setField(grantedAuthoritiesLevelsHolder, "userDao", userDao);

        ResultActions result = mockMvc.perform(post( controllerUrl + "/action")
            .contentType(MediaType.APPLICATION_JSON_UTF8)
            .content(json));

        // then
        result
            .andExpect(status().isOk());
    }
}

这是我试图注入模拟的类:

@Component
@Scope(value="session", proxyMode = ScopedProxyMode.TARGET_CLASS)
public class GrantedAuthoritiesLevelsHolder {

    @Autowired
    private UserDao userDao;

        // some methods
}

【问题讨论】:

  • 你为什么在 GrantedAuthoritiesLevelsHolder 对象上使用@Autowired
  • 为了在 Spring 测试中模拟事物,我使用 Spring 中的 @MockBean 注解。你试过了吗?

标签: java spring mockito junit4


【解决方案1】:

在加载上下文时,您必须将模拟 bean 注册为 UserDao。您可以如下所示进行注册。把它放在任何用@Configuration注释的类中

@Bean
@Primary
public UserDao UserDao() {
    return mock(UserDao.class);
}

【讨论】:

  • 谢谢Yogesh!这当然有帮助!知道为什么 Mockito.when() 不会触发吗?模拟返回 null...
【解决方案2】:

我相信您的配置可能不足以将模拟放入 Spring 上下文中。

我的建议:

@MockBean(answer=Answers.RETURNS_SMART_NULLS)
UserDao userDao;

@Autowired
GrantedAuthoritiesLevelsHolder grantedAuthoritiesLevelsHolder;

它应该将一个模拟放入 Spring 上下文中,而且它应该给你提示不正确/缺少存根的提示。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-05-28
    • 2019-06-16
    • 2015-12-10
    • 1970-01-01
    • 2012-10-31
    • 2013-08-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多