覆盖Mockito toString测试输出

dur*_*597 5 java junit hamcrest mockito

我写了一个定制的HamcrestMatcher<Double>来使用Mockito.doubleThat.

我想"覆盖toString()"方法,可以这么说,如果出现故障,错误会更加冗长.这是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)
Run Code Online (Sandbox Code Playgroud)

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

Argument(s) are different! Wanted:
dependedOnComponent.method(
    120 < matcher < 121
);
Run Code Online (Sandbox Code Playgroud)

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

Argument(s) are different! Wanted:
dependedOnComponent.method(
    1 < matcher < 200
);
Run Code Online (Sandbox Code Playgroud)

我不需要知道如何编写代码来生成数字或语法,我只需要知道WHERE来放置它.

dur*_*597 3

所以我做了一些愚蠢的事情;当我真正应该查看ArgumentMatcher的Javadoc 时,我正在阅读Matcher的 Javadoc 。

\n\n

一旦我意识到自己的错误,事情就很容易了;只需重写describeTo该接口中定义的方法,例如

\n\n
@Override\npublic void describeTo(Description description) {\n    description.appendText(String.valueOf(expected));\n    description.appendText(" \xc2\xb1 ");\n    description.appendText(String.valueOf(delta));\n}\n
Run Code Online (Sandbox Code Playgroud)\n