下面列出了怎么用org.mockito.exceptions.verification.WantedButNotInvoked的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* Function to verify that the DeletionService object received the right
* requests.
*
* @param delService the DeletionService mock which we verify against
*
* @param user the user name to use when verifying the deletion
*
* @param timeout amount in milliseconds to wait before we decide the calls
* didn't come through
*
* @param matchPaths the paths to match in the delete calls
*
* @throws WantedButNotInvoked if the calls could not be verified
*/
static void testDeletionServiceCall(DeletionService delService, String user,
long timeout, Path... matchPaths) {
long verifyStartTime = System.currentTimeMillis();
WantedButNotInvoked notInvokedException = null;
boolean matched = false;
while (!matched && System.currentTimeMillis() < verifyStartTime + timeout) {
try {
verify(delService).delete(eq(user), (Path) eq(null),
Mockito.argThat(new DeletePathsMatcher(matchPaths)));
matched = true;
} catch (WantedButNotInvoked e) {
notInvokedException = e;
try {
Thread.sleep(50l);
} catch (InterruptedException i) {
}
}
}
if (!matched) {
throw notInvokedException;
}
return;
}
/**
* Function to verify that the DeletionService object received the right
* requests.
*
* @param delService the DeletionService mock which we verify against
*
* @param user the user name to use when verifying the deletion
*
* @param timeout amount in milliseconds to wait before we decide the calls
* didn't come through
*
* @param matchPaths the paths to match in the delete calls
*
* @throws WantedButNotInvoked if the calls could not be verified
*/
static void testDeletionServiceCall(DeletionService delService, String user,
long timeout, Path... matchPaths) {
long verifyStartTime = System.currentTimeMillis();
WantedButNotInvoked notInvokedException = null;
boolean matched = false;
while (!matched && System.currentTimeMillis() < verifyStartTime + timeout) {
try {
verify(delService).delete(eq(user), (Path) eq(null),
Mockito.argThat(new DeletePathsMatcher(matchPaths)));
matched = true;
} catch (WantedButNotInvoked e) {
notInvokedException = e;
try {
Thread.sleep(50l);
} catch (InterruptedException i) {
}
}
}
if (!matched) {
throw notInvokedException;
}
return;
}
public void wantedButNotInvoked(PrintableInvocation wanted, List<? extends PrintableInvocation> invocations) {
String allInvocations;
if (invocations.isEmpty()) {
allInvocations = "Actually, there were zero interactions with this mock.\n";
} else {
StringBuilder sb = new StringBuilder("\nHowever, there were other interactions with this mock:\n");
for (PrintableInvocation i : invocations) {
sb.append(i.getLocation());
sb.append("\n");
}
allInvocations = sb.toString();
}
String message = createWantedButNotInvokedMessage(wanted);
throw new WantedButNotInvoked(message + allInvocations);
}
@Test
public void shouldArrayEqualsDealWithNullArray() throws Exception {
Object[] nullArray = null;
when(mock.oneArray(aryEq(nullArray))).thenReturn("null");
assertEquals("null", mock.oneArray(nullArray));
mock = mock(IMethods.class);
try {
verify(mock).oneArray(aryEq(nullArray));
fail();
} catch (WantedButNotInvoked e) {
assertContains("oneArray(null)", e.getMessage());
}
}
@Test
public void shouldPrintVerificationInOrderErrorAndShowWantedOnly() {
try {
inOrder.verify(one).differentMethod();
fail();
} catch (WantedButNotInvoked e) {
String expected =
"\n" +
"Wanted but not invoked:" +
"\n" +
"iMethods.differentMethod();" +
"\n" +
"-> at";
assertContains(expected, e.getMessage());
}
}
@Test
public void shouldVerifyUsingSameMatcher() {
Object one = new String("1243");
Object two = new String("1243");
Object three = new String("1243");
assertNotSame(one, two);
assertEquals(one, two);
assertEquals(two, three);
mock.oneArg(one);
mock.oneArg(two);
verify(mock).oneArg(same(one));
verify(mock, times(2)).oneArg(two);
try {
verify(mock).oneArg(same(three));
fail();
} catch (WantedButNotInvoked e) {}
}
@Test
public void shouldPrintMethodName() {
try {
verify(mock).simpleMethod();
fail();
} catch (WantedButNotInvoked e) {
String actualMessage = e.getMessage();
String expectedMessage =
"\n" +
"Wanted but not invoked:" +
"\n" +
"iMethods.simpleMethod();" +
"\n" +
"-> at";
assertContains(expectedMessage, actualMessage);
}
}
public void wantedButNotInvoked(DescribedInvocation wanted, List<? extends DescribedInvocation> invocations) {
String allInvocations;
if (invocations.isEmpty()) {
allInvocations = "Actually, there were zero interactions with this mock.\n";
} else {
StringBuilder sb = new StringBuilder("\nHowever, there were other interactions with this mock:\n");
for (DescribedInvocation i : invocations) {
sb.append(i.toString())
.append("\n")
.append(i.getLocation())
.append("\n\n");
}
allInvocations = sb.toString();
}
String message = createWantedButNotInvokedMessage(wanted);
throw new WantedButNotInvoked(message + allInvocations);
}
@Test
public void shouldArrayEqualsDealWithNullArray() throws Exception {
Object[] nullArray = null;
when(mock.oneArray(aryEq(nullArray))).thenReturn("null");
assertEquals("null", mock.oneArray(nullArray));
mock = mock(IMethods.class);
try {
verify(mock).oneArray(aryEq(nullArray));
fail();
} catch (WantedButNotInvoked e) {
assertContains("oneArray(null)", e.getMessage());
}
}
@Test
public void shouldPrintVerificationInOrderErrorAndShowWantedOnly() {
try {
inOrder.verify(one).differentMethod();
fail();
} catch (WantedButNotInvoked e) {
String expected =
"\n" +
"Wanted but not invoked:" +
"\n" +
"iMethods.differentMethod();" +
"\n" +
"-> at";
assertContains(expected, e.getMessage());
}
}
@Test
public void shouldVerifyUsingSameMatcher() {
Object one = new String("1243");
Object two = new String("1243");
Object three = new String("1243");
assertNotSame(one, two);
assertEquals(one, two);
assertEquals(two, three);
mock.oneArg(one);
mock.oneArg(two);
verify(mock).oneArg(same(one));
verify(mock, times(2)).oneArg(two);
try {
verify(mock).oneArg(same(three));
fail();
} catch (WantedButNotInvoked e) {}
}
@Test
public void should_print_method_name() {
try {
verify(mock).simpleMethod();
fail();
} catch (WantedButNotInvoked e) {
String actualMessage = e.getMessage();
String expectedMessage =
"\n" +
"Wanted but not invoked:" +
"\n" +
"iMethods.simpleMethod();" +
"\n" +
"-> at";
assertContains(expectedMessage, actualMessage);
}
}
@Test
@Ignore("issue 380 related")
public void should_print_method_name_and_arguments_of_other_interactions_of_same_method() throws Exception {
try {
mock.forByte((byte) 25);
mock.forByte((byte) 12);
verify(mock).forByte((byte) 42);
fail();
} catch (WantedButNotInvoked e) {
System.out.println(e);
assertContains("iMethods.forByte(42)", e.getMessage());
assertContains("iMethods.forByte(25)", e.getMessage());
assertContains("iMethods.forByte(12)", e.getMessage());
}
}
@Test
public void verifyPolicyExecutionOrder() throws Exception {
List<Measurement> measurements = new ArrayList<>();
List<Symptom> symptoms = new ArrayList<>();
List<Diagnosis> diagnosis = new ArrayList<>();
List<Action> actions = new ArrayList<>();
IHealthPolicy mockPolicy = mock(IHealthPolicy.class);
when(mockPolicy.getDelay()).thenReturn(Duration.ZERO);
when(mockPolicy.executeSensors()).thenReturn(measurements);
when(mockPolicy.executeDetectors(measurements)).thenReturn(symptoms);
when(mockPolicy.executeDiagnosers(symptoms)).thenReturn(diagnosis);
when(mockPolicy.executeResolvers(diagnosis)).thenReturn(actions);
List<IHealthPolicy> policies = Collections.singletonList(mockPolicy);
PoliciesExecutor executor = new PoliciesExecutor(policies);
ScheduledFuture<?> future = executor.start();
try {
verify(mockPolicy, timeout(200l).atLeastOnce()).executeResolvers(diagnosis);
} catch (WantedButNotInvoked e) {
if (future.isDone()) {
System.out.println(future.get());
}
throw e;
}
InOrder order = Mockito.inOrder(mockPolicy);
order.verify(mockPolicy).executeSensors();
order.verify(mockPolicy).executeDetectors(measurements);
order.verify(mockPolicy).executeDiagnosers(symptoms);
order.verify(mockPolicy).executeResolvers(diagnosis);
executor.destroy();
}
public static String getEvents(EventListener events) {
try {
ArgumentCaptor<Events> captor = ArgumentCaptor.forClass(Events.class);
verify(events, atLeast(1)).event(captor.capture());
return captor.getAllValues().toString();
} catch (WantedButNotInvoked e) {
return "[]";
} finally {
reset(events);
}
}
@Test
public void shouldPrintCaptorMatcher() {
//given
ArgumentCaptor<Person> person = ArgumentCaptor.forClass(Person.class);
try {
//when
verify(emailService).sendEmailTo(person.capture());
fail();
} catch(WantedButNotInvoked e) {
//then
assertContains("<Capturing argument>", e.getMessage());
}
}
@Test
public void deltaMatcherPrintsItself() {
try {
verify(mock).oneArg(eq(1.0D, 0.1D));
fail();
} catch (WantedButNotInvoked e) {
assertContains("eq(1.0, 0.1)", e.getMessage());
}
}
@Test
public void shouldNotThrowSmartNullPointerOnToString() {
Object smartNull = mock.objectReturningMethod();
try {
verify(mock).simpleMethod(smartNull);
fail();
} catch (WantedButNotInvoked e) {}
}
@Test
public void shouldUseArgumentTypeWhenOverloadingPuzzleDetected() throws Exception {
Sub sub = mock(Sub.class);
setMockWithDowncast(sub);
say("Hello");
try {
verify(sub).say("Hello");
fail();
} catch (WantedButNotInvoked e) {}
}
@Test
public void shouldFilterStackTraceOnVerify() {
try {
verify(mock).simpleMethod();
fail();
} catch (WantedButNotInvoked e) {
assertThat(e, hasFirstMethodInStackTrace("shouldFilterStackTraceOnVerify"));
}
}
@Test
public void shouldDetectActualInvocationsCountIsMoreThanZero() throws Exception {
verify(mock, times(0)).clear();
try {
verify(mock, times(15)).clear();
fail();
} catch (WantedButNotInvoked e) {}
}
@Test
public void shouldShowAllInteractionsOnMockWhenOrdinaryVerificationFail() throws Exception {
firstInteraction();
secondInteraction();
try {
verify(mock).simpleMethod();
fail();
} catch (WantedButNotInvoked e) {
assertContains("However, there were other interactions with this mock", e.getMessage());
assertContains("firstInteraction(", e.getMessage());
assertContains("secondInteraction(", e.getMessage());
}
}
@Test
public void shouldNotShowAllInteractionsOnDifferentMock() throws Exception {
differentMockInteraction();
firstInteraction();
try {
verify(mock).simpleMethod();
fail();
} catch (WantedButNotInvoked e) {
assertContains("firstInteraction(", e.getMessage());
assertNotContains("differentMockInteraction(", e.getMessage());
}
}
@Test
public void shouldNotShowAllInteractionsHeaderWhenNoOtherInteractions() throws Exception {
try {
verify(mock).simpleMethod();
fail();
} catch (WantedButNotInvoked e) {
assertContains("there were zero interactions with this mock.", e.getMessage());
}
}
@Test
public void shouldFailIfMethodWasNotInvoked() {
mock.clear();
try {
verify(mock, only()).get(0);
fail();
} catch (WantedButNotInvoked e) {}
}
@Test
public void shouldFailIfMethodWasInvokedButWithDifferentArguments() {
mock.get(0);
mock.get(2);
try {
verify(mock, only()).get(999);
fail();
} catch (WantedButNotInvoked e) {}
}
@Test
public void shouldMessagesPointToProperMethod() {
mockTwo.differentMethod();
mockOne.simpleMethod();
try {
inOrder.verify(mockOne, atLeastOnce()).differentMethod();
fail();
} catch (WantedButNotInvoked e) {
assertContains("differentMethod()", e.getMessage());
}
}
@Test
public void shouldPrintMethodNameAndArguments() {
try {
verify(mock).threeArgumentMethod(12, new Foo(), "xx");
fail();
} catch (WantedButNotInvoked e) {
assertContains("iMethods.threeArgumentMethod(12, foo, \"xx\")", e.getMessage());
}
}
@Test
public void shouldPrintMethodNameWhenVerifyingAtLeastOnce() throws Exception {
try {
verify(mock, atLeastOnce()).twoArgumentMethod(1, 2);
fail();
} catch (WantedButNotInvoked e) {
assertContains("twoArgumentMethod(1, 2)", e.getMessage());
}
}
@Test
public void shouldPrintMethodWhenMatcherUsed() throws Exception {
try {
verify(mock, atLeastOnce()).twoArgumentMethod(anyInt(), eq(100));
fail();
} catch (WantedButNotInvoked e) {
String actualMessage = e.getMessage();
String expectedMessage =
"\n" +
"Wanted but not invoked:" +
"\n" +
"iMethods.twoArgumentMethod(<any>, 100);";
assertContains(expectedMessage, actualMessage);
}
}