在执行涉及包含verify.save((方法的方法的JUnit测试用例时,我收到以下错误"参数不同!通缉令'
@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)
你应该使用:
verify(attemptRepository).save(Matchers.refEq(verifiedAttempt));
我怀疑MultiplicationResultAttempt
不会在对象的字段上实现基于相等的等于,因此当 Mockito 验证属性时,它不等于您提供的对象,尽管所有字段都具有相同的值。
Matcher.refEq(...)
使用反射来确定值是否相同。
编辑
正如@farhanlq指出的那样Matchers.refEq(..)
已弃用,应该改用ArgumentMatchers.refEq(...)
。
我确实在MultiplicationResultAttempt
中实现了等于和哈希代码,并且它起作用了!!