在执行涉及包含verify.save()方法的方法的 JUnit 测试用例时,我遇到以下错误 'Argument(s)不同!想要的
@Test
public void checkCorrectAttemptTest() {
Multiplication multiplication = new Multiplication(50, 60);
User user = new User("abc");
MultiplicationResultAttempt attempt = new MultiplicationResultAttempt(user, multiplication, 3000, false);
MultiplicationResultAttempt verifiedAttempt = new MultiplicationResultAttempt(user, multiplication, 3000, true);
when(userRepository.findByAlias("abc")).thenReturn(Optional.empty());
boolean attemptResult = multiplicaitonServiceImpl.checkAttempt(attempt);
assertThat(attemptResult).isTrue();
verify(attemptRepository).save(verifiedAttempt);
}
我收到以下错误消息。
Argument(s) are different! Wanted:
attemptRepository.save(
MultiplicationResultAttempt [user=User [alias=abc], multiplication=Multiplication [factorA=50, factorB=60], resultAttempt=3000, correct=true]
);
-> at microservices.book.multiplication.service.MultiplicationServiceImplTest.checkCorrectAttemptTest(MultiplicationServiceImplTest.java:60)
Actual invocation has different arguments:
attemptRepository.save(
MultiplicationResultAttempt [user=User [alias=abc], multiplication=Multiplication [factorA=50, factorB=60], resultAttempt=3000, correct=true]
);
-> at microservices.book.multiplication.service.MultiplicationServiceImpl.checkAttempt(MultiplicationServiceImpl.java:58)
at microservices.book.multiplication.service.MultiplicationServiceImplTest.checkCorrectAttemptTest(MultiplicationServiceImplTest.java:60)
答案 0 :(得分:1)
我确实在 MultiplicationResultAttempt
中实现了 equals 和 hashcode,并且成功了!!!
答案 1 :(得分:0)
您应该使用:
verify(attemptRepository).save(Matchers.refEq(verifiedAttempt));
我怀疑MultiplicationResultAttempt
不能基于对象字段的相等性来实现equals,因此,当Mockito验证属性时,它不等于您提供的对象,尽管所有字段都具有相同的值
Matcher.refEq(...)
使用反射来确定值是否相同。
修改
@farhanlq指出Matchers.refEq(..)
已过时,应改为使用ArgumentMatchers.refEq(...)
。