我有这个方法签名,我想用EasyMock模拟
public BigDecimal getRemainingPremium(BigDecimal baseAmount, Date commencementDate, Date effectiveDate, boolean isComplete)
我的测试代码有
Premium premium = createMock(Premium.class);
// add this line
EasyMock.expect(premium.getCommencementDate()).andReturn(EasyMock.anyObject(Date.class)).anyTimes();
expect(
premium.getRemainingPremium(
EasyMock.anyObject(BigDecimal.class),
EasyMock.anyObject(Date.class),
EasyMock.anyObject(Date.class),
EasyMock.anyBoolean()
))
.andReturn(BigDecimal.TEN).anyTimes();
但我一直收到这个匹配器异常。我已经尝试了所有原语和'EasyMock.anyObject(Boolean.class)'的组合。有任何解决方法的建议吗?
java.lang.IllegalStateException: 4 matchers expected, 5 recorded.
This exception usually occurs when matchers are mixed with raw values when recording a method:
foo(5, eq(6)); // wrong
You need to use no matcher at all or a matcher for every single param:
foo(eq(5), eq(6)); // right
foo(5, 6); // also right
at org.easymock.internal.ExpectedInvocation.createMissingMatchers(ExpectedInvocation.java:48)
at org.easymock.internal.ExpectedInvocation.<init>(ExpectedInvocation.java:41)
at org.easymock.internal.RecordState.invoke(RecordState.java:79)
at org.easymock.internal.MockInvocationHandler.invoke(MockInvocationHandler.java:41)
最佳答案
您在使用匹配器时应使用实际对象。
EasyMock.expect(premium.getCommencementDate()).andReturn(EasyMock.anyObject(Date.class)).anyTimes();
在上面的行中,您已经真正使用
anyObject()
对象使用了Date
匹配器。我想知道您是否在这种意义上将匹配器与模拟混淆。
anyObject()
匹配器是一种确认使用Date
类型的对象调用的方法的方法。它不会创建可用作Date
类实例的日期对象。为此,您需要创建一个Date
的模拟实例。因此,请记住,匹配器应该用作模拟方法的参数,而不是返回值。以下期望将解决您的问题:
Date mockDate = EasyMock.createMock(Date.class);
final IPremium premium = EasyMock.createMock(IPremium.class);
EasyMock.expect(premium.getCommencementDate()).andReturn(mockDate).anyTimes();
expect(
premium.getRemainingPremium(
(BigDecimal) EasyMock.anyObject(),
(Date) EasyMock.anyObject(),
(Date) EasyMock.anyObject(),
EasyMock.anyBoolean()
))
.andReturn(BigDecimal.TEN).anyTimes();
replay(premium);
关于java - EasyMock-匹配器与原始值混合在一起吗?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/22512927/