为什么这个mockito不会嘲笑

时间:2017-03-21 01:51:11

标签: spring-mvc mockito

这是测试类:

@MockBean
private UserRepository userRepository;

@Before
public void beforeClass() {
    String mobile;
    when(this.userRepository.findByMobile(Mockito.anyString())).thenAnswer(new Answer<User>() {
        @Override
        public User answer(InvocationOnMock invocation) throws Throwable {
            Object[] args = invocation.getArguments();
            return MockData.getUserByMobile((String) args[0]);
        }
    });
}

@Test
@WithUserDetails(value = MockData.CUSTOMER_USERNAME, userDetailsServiceBeanName = "customizedUserDetailsService")
public void testAdd() throws Exception {}

这是userDetails实施:

@Autowired
private UserRepository userRepository;

@Override
@Transactional
public UserDetails loadUserByUsername(String username) {
    User user = (User) userRepository.findByMobile(username); // user is always null 

我希望在调用userRepository.findByMobile时,它应该调用getUserByMobile中定义的@Before方法。但显然Mockito配置不起作用或userRepository无法模拟。怎么了,怎么解决?

1 个答案:

答案 0 :(得分:2)

UserDpository用于userDetails实现,需要按照this中的描述将其注入userDetails。但是因为XXRepository在接口中,所以不能使用@InjectedMock。然后课程成为: 考试类:

    @MockBean
    private UserService userService;

    @InjectMocks
    private CustomizedUserDetailsService customizedUserDetailsService;

    @Before
    public void before() {
        MockitoAnnotations.initMocks(this);
        when(this.userService.findByMobile(Mockito.anyString())).thenAnswer(new Answer<User>() {
            @Override
            public User answer(InvocationOnMock invocation) throws Throwable {
                Object[] args = invocation.getArguments();
                return MockData.getUserByMobile((String) args[0]);
            }
        });
    }

    @Test
    @WithUserDetails(value = MockData.CUSTOMER_USERNAME, userDetailsServiceBeanName = "customizedUserDetailsService") {}

userDetails:

@Autowired
private UserService userService;

@Override
@Transactional
public UserDetails loadUserByUsername(String username) {
    User user = (User) userService.findByMobile(username);

我可以看到userDetails中的userService与测试类中模拟的userService相同,但@Before之后调用@WithUserDetails userDetails方法。所以最后为了实现加载MockData用户,我想我必须为UT创建另一个userDetails。编辑2:实际上,我已经尝试过没有@InjectMocks并使用userService(最初我使用的是userRepository),它也可以。