与Mockito模拟互动时发生ClassCastException

时间:2019-02-28 12:02:01

标签: java spring mockito

我有一个简单的课程

public class UserService {
    private final UserRepository userRepository;

    @Autowired
    public UserService(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    public void send(Long id) {
        User user = userRepository.findById(id).orElseThrow(NotFoundException::new);
        //other logic
        userRepository.save(user);
    }
}

和单元测试

@Test
public void sendShouldUpdateIsFinalField() {
    Long id = 44L;
    User user = new User();

    when(userRepository.findById(id)).thenReturn(Optional.of(user));
    when(userRepository.save(user)).then(a -> (Answer) invocationOnMock -> {
        assertTrue(user.getIsFinal());
        return null;
    });

    userService.send(id);
    verify(userRepository, times(1)).save(user);
}

当我运行此测试时,它失败并出现java.lang.ClassCastException:user.service.UserServiceTest $$ Lambda $ 3/899543194无法转换为user.model.User

在UserService的此行上

userRepository.save(user);

这是什么问题?谢谢。

1 个答案:

答案 0 :(得分:3)

您在第二个Mockito.when()中创建两个lambda:

when(userRepository.save(user)).then(a -> (Answer) invocationOnMock -> {
---------------------------------------^^---------------------------^^

您只需要一个,因此完全删除(Answer) invocationOnMock ->

when(userRepository.save(user)).then(a -> {