EasyMock - 匹配器与原始值混合在一起?

时间:2014-03-19 16:56:58

标签: java easymock

我有这个方法签名,我想用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)

1 个答案:

答案 0 :(得分:8)

您正在使用匹配器,您应该使用实际对象。

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);