覆盖Mockito toString测试输出

时间:2014-05-23 14:01:37

标签: java junit mockito hamcrest

我已经编写了一个与Hamcrest Matcher<Double>一起使用的自定义Mockito.doubleThat

我想&#34;覆盖toString()&#34;方法,可以这么说,如果出现故障,则错误更加冗长。这是JUnit失败追踪:

Argument(s) are different! Wanted:
dependedOnComponent.method(
    <Double matcher>
);
-> at my.domain.TestClass.testMethod(TestClass.java:123)
Actual invocation has different arguments:
dependedOnComponent.method(
    123.45,
);
-> at my.domain.SystemUnderTest.callingMethod(SystemUnderTest.java:456)

如您所见,它会打印<Double matcher>。是否可以覆盖该消息?相反,我想看看,作为一个例子:

Argument(s) are different! Wanted:
dependedOnComponent.method(
    120 < matcher < 121
);

但我的匹配器类的不同实例可能是:

Argument(s) are different! Wanted:
dependedOnComponent.method(
    1 < matcher < 200
);

我不需要知道如何编写代码来生成数字或语法,我只需知道将其放在哪里。

2 个答案:

答案 0 :(得分:3)

所以我做的事情很傻;当我真的应该查看Javadoc Matcher时,我正在阅读ArgumentMatcher的Javadoc。

一旦我意识到自己的错误,这很容易;只需覆盖该界面中定义的describeTo方法,例如

@Override
public void describeTo(Description description) {
    description.appendText(String.valueOf(expected));
    description.appendText(" ± ");
    description.appendText(String.valueOf(delta));
}

答案 1 :(得分:2)

尝试以下方法:

@RunWith(MockitoJUnitRunner.class)
public class SOTest {

    public interface Foo {
        void doSomething(double d);
    }

    @Test
    public void sillyTest() {

        Foo foo = mock(Foo.class);
        foo.doSomething(1);
        verify(foo).doSomething(Mockito.doubleThat(new TestMatcher(2)));
    }

    public class TestMatcher extends CustomMatcher<Double> {

        private final double expected;

        public TestMatcher(double expected) {
            super(Double.toString(expected));
            this.expected = expected;
        }

        @Override
        public boolean matches(Object item) {
            return item instanceof Double && ((Double) item).equals(expected);
        }
    }
}

输出:

Argument(s) are different! Wanted:
foo.doSomething(2.0);
-> at SOTest.sillyTest(SOTest.java:23)
Actual invocation has different arguments:
foo.doSomething(1.0);
-> at SOTest.sillyTest(SOTest.java:22)