Spring Boot, Mockito, injecting mock into scope session bean

问题: I'm having a problem injecting mock into one class I need for testing. I'm trying to mock a Dao class and had no problem doing so using ReflectionTestUtils in various servi...

问题:

I'm having a problem injecting mock into one class I need for testing. I'm trying to mock a Dao class and had no problem doing so using ReflectionTestUtils in various services I'm using, however this one just does not want to work, it keeps calling the Dao class and getting errors from the database.

This is the test class:

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

And this is the class I'm trying to inject mock into:

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

    @Autowired
    private UserDao userDao;

        // some methods
}

回答1:

I believe that your configuration may be not enough to put a mock into Spring context.

My advice:

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

@Autowired
GrantedAuthoritiesLevelsHolder grantedAuthoritiesLevelsHolder;

It should put a mock into Spring context, moreover it should give you hints with incorrect/missing stubbing.


回答2:

You will have to register mocked bean as UserDao when the context is getting loaded. You can register it as shown below. Put this in any class annotated with @Configuration

@Bean
@Primary
public UserDao UserDao() {
    return mock(UserDao.class);
}
  • 发表于 2018-09-02 03:23
  • 阅读 ( 321 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除