/** * 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 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()); } }
protected void verifyCalledEventually(int timeoutSecs, Runnable r) { for (int i = 0; i < timeoutSecs; i++) { try { r.run(); System.err.println("Verified invocation after " + i + " sec"); return; // succeeded } catch (Throwable t) { if (t instanceof java.lang.AssertionError || t instanceof WantedButNotInvoked || t instanceof org.mockito.exceptions.verification.ArgumentsAreDifferent || t instanceof org.mockito.exceptions.verification.junit.ArgumentsAreDifferent) { try { Thread.sleep(1000); } catch (InterruptedException ee) { throw new RuntimeException(ee); } } else { System.err.println(t.getClass().getName() + ": "); t.printStackTrace(); throw new RuntimeException(t); } } } throw new RuntimeException("verifyCalledEventually failed after " + timeoutSecs + " seconds"); }
@Test public void checkForInvalidViews() throws Exception { sqlExecutor.executeWithinContext(physicalSchema, new Procedure<Connection>() { @Override public void value(Connection conn) { // Setup the invalid objects try { sqlExecutor.getJdbcTemplate().update(conn, "drop table INVALIDTEST_TABLE"); } catch (DataAccessException ignore) { // ignore exceptions on dropping } sqlExecutor.getJdbcTemplate().update(conn, "create table INVALIDTEST_TABLE (a INT)"); sqlExecutor.getJdbcTemplate().update(conn, "create or replace view INVALIDTEST_VIEW AS SELECT * FROM INVALIDTEST_TABLE"); sqlExecutor.getJdbcTemplate().update(conn, "create or replace view INVALIDTEST_VIEW2 AS SELECT * FROM INVALIDTEST_VIEW WHERE 1=2"); sqlExecutor.getJdbcTemplate().update(conn, "drop table INVALIDTEST_TABLE"); MutableSet<String> invalidObjects = db2PostDeployAction.getInvalidObjects(conn, env.getPhysicalSchemas()).collect(Db2PostDeployAction.ReorgQueryResult.TO_NAME).toSet(); assertThat("The two views created should go invalid when we drop the table that they are based on", invalidObjects, hasItems("INVALIDTEST_VIEW", "INVALIDTEST_VIEW2")); // Check that the query can return invalid objects db2PostDeployAction.checkForInvalidObjects(conn, env.getPhysicalSchemas()); // With this DB2 version, verify that we did try to execute the recompile and that if it fails (which we expect to in this case) that we log a warning // (It is hard to simulate a case where a recopmile will fix things, compared to DB2's auto-recompile) try { verify(metricsCollector, times(1)).addMetric(Matchers.eq(Db2PostDeployAction.POST_DEPLOY_WARNINGS), Matchers.<Serializable>any()); } catch (WantedButNotInvoked e) { Assume.assumeNoException("Expecting view to be invalid, but was not in this case", e); } } }); }
@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); } }
@Test public void shouldPrintInteractionsOnMockWhenOrdinaryVerificationFail() throws Exception { mock.otherMethod(); mock.booleanReturningMethod(); try { verify(mock).simpleMethod(); fail(); } catch (WantedButNotInvoked e) { // assertContains("") } }
@Test public void shouldNeverBreakMethodStringWhenNoArgsInMethod() throws Exception { try { verify(veeeeeeeeeeeeeeeeeeeeeeeerylongNameMock).simpleMethod(); fail(); } catch(WantedButNotInvoked e) { assertContains("veeeeeeeeeeeeeeeeeeeeeeeerylongNameMock.simpleMethod()", e.getMessage()); } }
@Test public void shouldFailOnWrongMethod() throws Exception { mock.clear(); mock.clear(); mockTwo.add("add"); verify(mock, atLeastOnce()).clear(); verify(mockTwo, atLeastOnce()).add("add"); try { verify(mockTwo, atLeastOnce()).add("foo"); fail(); } catch (WantedButNotInvoked e) {} }
@Test public void shouldDetectWhenOverloadedMethodCalled() throws Exception { IMethods mockThree = mock(IMethods.class); mockThree.varargs((Object[]) new Object[] {}); try { verify(mockThree).varargs((String[]) new String[] {}); fail(); } catch(WantedButNotInvoked e) {} }
@Test public void pluginFiltersOutStackTraceElement() { try { MyStackTraceCleanerProvider.ENABLED = true; verifyMock_x(); fail(); } catch (WantedButNotInvoked e) { String trace = getStackTrace(e); assertContains("verifyMock_x", trace); assertNotContains("verify_excludeMe_x", trace); } }
@Test public void pluginDoesNotFilterOutStackTraceElement() { try { MyStackTraceCleanerProvider.ENABLED = false; verifyMock_x(); fail(); } catch (WantedButNotInvoked e) { String trace = getStackTrace(e); assertContains("verifyMock_x", trace); assertContains("verify_excludeMe_x", trace); } }
@Test public void should_print_captor_matcher() { //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()); } }