有没有办法让never()+ startsWith()匹配报告匹配什么?

时间:2015-01-23 19:39:33

标签: java mockito hamcrest

我有这个:

verify(logger, never()).info(startsWith("Created content from "));

错误信息是:

org.mockito.exceptions.verification.NeverWantedButInvoked: 
logger.info(
    startsWith("Created content from ")
);

因为我正在使用startsWith,所以查看完整字符串能够调试此故障的确非常有用。有没有办法得到那个字符串?

1 个答案:

答案 0 :(得分:1)

我认为你能做到这一点的唯一方法就是编写自己的匹配器。您可以在自己的实用程序类中粘贴一个返回匹配器的方法,例如......

public class CustomMatchers {
    public static String capturingStartsWith(final String expected) {
        return Mockito.argThat(new TypeSafeMatcher<String>() {

            private String actual;

            @Override
            public void describeTo(Description description) {
                description.appendText("String that starts with: ");
                description.appendValue(expected);
                description.appendText(" actual: ");
                description.appendValue(actual);
            }

            @Override
            protected boolean matchesSafely(String actual) {
                this.actual = actual;
                return actual.startsWith(expected);
            }
        });
    }
}

那你的考试......

import static CustomMatchers.*;
...
@Test
public void shouldNotDoWhatItDoesNow() {
    classUnderTest.doStuff();

    verify(logger, never()).info(capturingStartsWith("Created content from"));
}

这会给你这样的输出......

org.mockito.exceptions.verification.NeverWantedButInvoked: 
logger.info(
    Start that starts with: "Created content from" actual: "Created content from [WIBBLE]"
);
Never wanted here:
-> at  CustomStartsWithTest.shouldNotDoWhatItDoesNow(CustomStartsWithTest.java:28)
But invoked here:
-> at CustomStartsWith.doStuff(CustomStartsWith.java:12)

(在帮助器方法中没有将类型安全匹配器包装在&#34; argThat&#34;并返回匹配器可能更优雅)

我不知道有任何像这样的额外匹配器的免费库。可能有一种更聪明的方式来攻击Mockito为你做这件事......