org.mockito.exceptions.misusing.InvalidUseOfMatchersException Java Examples

The following examples show how to use org.mockito.exceptions.misusing.InvalidUseOfMatchersException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: InvalidStateDetectionTest.java    From astor with GNU General Public License v2.0 7 votes vote down vote up
@Test
public void shouldDetectMisplacedArgumentMatcher() {
    anyObject();
    detectsAndCleansUp(new OnStubVoid(), InvalidUseOfMatchersException.class);
    
    anyObject();
    detectsAndCleansUp(new OnVerify(), InvalidUseOfMatchersException.class);
    
    anyObject();
    detectsAndCleansUp(new OnVerifyInOrder(), InvalidUseOfMatchersException.class);
    
    anyObject();
    detectsAndCleansUp(new OnVerifyZeroInteractions(), InvalidUseOfMatchersException.class);
    
    anyObject();
    detectsAndCleansUp(new OnVerifyNoMoreInteractions(), InvalidUseOfMatchersException.class);
    
    anyObject();
    detectsAndCleansUp(new OnDoAnswer(), InvalidUseOfMatchersException.class);
}
 
Example #2
Source File: AS2MessageMDNTest.java    From OpenAs2App with BSD 2-Clause "Simplified" License 7 votes vote down vote up
@Before
public void setUp() throws Exception {
    when(message.getPartnership()).thenReturn(partnership);
    when(partnership.getReceiverID(matches(Partnership.PID_AS2))).thenReturn("receiverId");
    when(partnership.getSenderID(matches(Partnership.PID_AS2))).thenReturn("senderId");
    when(message.getPartnership().getAttributeOrProperty(anyString(), any())).thenAnswer(new Answer<Object>() {
        @Override
        public Object answer(InvocationOnMock invocation) throws Throwable {
            Object argument = invocation.getArguments()[0];
            if (argument.toString().equals(Properties.AS2_MDN_MESSAGE_ID_FORMAT)) {
                if (returnMdnFmt) {
                    return msgIdMdnFmt;
                } else {
                    return null;
                }
            } else if (argument.toString().equals(Properties.AS2_MESSAGE_ID_FORMAT)) {
                return msgIdFmt;
            } else if (argument.toString().equals(Properties.AS2_MESSAGE_ID_ENCLOSE_IN_BRACKETS)) {
                return "true";
            }
            throw new InvalidUseOfMatchersException(String.format("Argument %s does not match", argument));
        }
    });
}
 
Example #3
Source File: MockHandlerTest.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void shouldRemoveVerificationModeEvenWhenInvalidMatchers() throws Throwable {
    //given
    Invocation invocation = new InvocationBuilder().toInvocation();
    MockHandler handler = new MockHandler();
    handler.mockingProgress.verificationStarted(VerificationModeFactory.atLeastOnce());
    handler.matchersBinder = new MatchersBinder() {
        public InvocationMatcher bindMatchers(ArgumentMatcherStorage argumentMatcherStorage, Invocation invocation) {
            throw new InvalidUseOfMatchersException();
        }
    };
    
    try {
        //when
        handler.handle(invocation);
        
        //then
        fail();
    } catch (InvalidUseOfMatchersException e) {}
    
    assertNull(handler.mockingProgress.pullVerificationMode());
}
 
Example #4
Source File: MockHandlerImplTest.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void shouldRemoveVerificationModeEvenWhenInvalidMatchers() throws Throwable {
	// given
	Invocation invocation = new InvocationBuilder().toInvocation();
	@SuppressWarnings("rawtypes")
       MockHandlerImpl<?> handler = new MockHandlerImpl(new MockSettingsImpl());
	handler.mockingProgress.verificationStarted(VerificationModeFactory.atLeastOnce());
	handler.matchersBinder = new MatchersBinder() {
		public InvocationMatcher bindMatchers(ArgumentMatcherStorage argumentMatcherStorage, Invocation invocation) {
			throw new InvalidUseOfMatchersException();
		}
	};

	try {
		// when
		handler.handle(invocation);

		// then
		fail();
	} catch (InvalidUseOfMatchersException e) {
	}

	assertNull(handler.mockingProgress.pullVerificationMode());
}
 
Example #5
Source File: DetectingMisusedMatchersTest.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void should_report_argument_locations_when_argument_matchers_misused() {
    try {
    	Observer observer = mock(Observer.class);
    	
    	misplaced_anyInt_argument_matcher();
    	misplaced_anyObject_argument_matcher();
    	misplaced_anyBoolean_argument_matcher();
    	
    	observer.update(null, null);
    	
    	validateMockitoUsage();
    	fail();
    } catch (InvalidUseOfMatchersException e) {
        assertContains("DetectingMisusedMatchersTest.misplaced_anyInt_argument_matcher", e.getMessage());
        assertContains("DetectingMisusedMatchersTest.misplaced_anyObject_argument_matcher", e.getMessage());
        assertContains("DetectingMisusedMatchersTest.misplaced_anyBoolean_argument_matcher", e.getMessage());
    }
}
 
Example #6
Source File: InvalidStateDetectionTest.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void shouldDetectMisplacedArgumentMatcher() {
    anyObject();
    detectsAndCleansUp(new OnStubVoid(), InvalidUseOfMatchersException.class);
    
    anyObject();
    detectsAndCleansUp(new OnVerify(), InvalidUseOfMatchersException.class);
    
    anyObject();
    detectsAndCleansUp(new OnVerifyInOrder(), InvalidUseOfMatchersException.class);
    
    anyObject();
    detectsAndCleansUp(new OnVerifyZeroInteractions(), InvalidUseOfMatchersException.class);
    
    anyObject();
    detectsAndCleansUp(new OnVerifyNoMoreInteractions(), InvalidUseOfMatchersException.class);
    
    anyObject();
    detectsAndCleansUp(new OnDoAnswer(), InvalidUseOfMatchersException.class);
}
 
Example #7
Source File: Reporter.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
public void misplacedArgumentMatcher(Location location) {
    throw new InvalidUseOfMatchersException(join(
            "Misplaced argument matcher detected here:",
            location,
            "",
            "You cannot use argument matchers outside of verification or stubbing.",
            "Examples of correct usage of argument matchers:",
            "    when(mock.get(anyInt())).thenReturn(null);",
            "    doThrow(new RuntimeException()).when(mock).someVoidMethod(anyObject());",
            "    verify(mock).someMethod(contains(\"foo\"))",
            "",
            "Also, this error might show up because you use argument matchers with methods that cannot be mocked.",
            "Following methods *cannot* be stubbed/verified: final/private/equals()/hashCode().",
            ""
            ));
}
 
Example #8
Source File: Reporter.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
public void invalidUseOfMatchers(int expectedMatchersCount, int recordedMatchersCount) {
    throw new InvalidUseOfMatchersException(join(
            "Invalid use of argument matchers!",
            expectedMatchersCount + " matchers expected, " + recordedMatchersCount + " recorded.",
            "This exception may occur if matchers are combined with raw values:",
            "    //incorrect:",
            "    someMethod(anyObject(), \"raw String\");",
            "When using matchers, all arguments have to be provided by matchers.",
            "For example:",
            "    //correct:",
            "    someMethod(anyObject(), eq(\"String by matcher\"));",
            "",
            "For more info see javadoc for Matchers class."
    ));
}
 
Example #9
Source File: ExplicitFrameworkValidationTest.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void shouldDetectMisplacedArgumentMatcher() {
    anyObject();
    try {
        Mockito.validateMockitoUsage();
        fail();
    } catch (InvalidUseOfMatchersException e) {}
}
 
Example #10
Source File: InvalidUseOfMatchersTest.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void should_scream_when_Matchers_count_dont_match_parameter_count() {
    try {
        mock.threeArgumentMethod(1, "asd", eq("asd"));
        fail();
    } catch (InvalidUseOfMatchersException e) {
        assertThat(e.getMessage())
                  .contains("3 matchers expected")
                  .contains("1 recorded");
    }
}
 
Example #11
Source File: InvalidUseOfMatchersTest.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void should_scream_when_not_enough_matchers_inside_or_AddtionalMatcher() {
    try {
        mock.simpleMethod(AdditionalMatchers.or(eq("jkl"), "asd"));
        fail();
    } catch (InvalidUseOfMatchersException e) {
        assertThat(e.getMessage())
                .containsIgnoringCase("inside additional matcher Or(?)")
                .contains("2 sub matchers expected")
                .contains("1 recorded");
    }
}
 
Example #12
Source File: InvalidUseOfMatchersTest.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void should_scream_when_no_matchers_inside_not() {
    try {
        mock.simpleMethod(AdditionalMatchers.not("jkl"));
        fail();
    } catch (InvalidUseOfMatchersException e) {
        assertThat(e.getMessage())
                .contains("No matchers found for")
                .containsIgnoringCase("Not(?)");
    }
}
 
Example #13
Source File: InvalidUseOfMatchersTest.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void should_detect_stupid_use_of_matchers_when_verifying() {
    mock.oneArg(true);
    eq("that's the stupid way");
    eq("of using matchers");
    try {
        Mockito.verify(mock).oneArg(true);
        fail();
    } catch (InvalidUseOfMatchersException e) {
        assertThat(e.getMessage())
                  .contains("Misplaced argument matcher detected here");
        e.printStackTrace();
    }
}
 
Example #14
Source File: InvalidUseOfMatchersTest.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void should_detect_wrong_number_of_matchers_when_stubbing() {
    when(mock.threeArgumentMethod(1, "2", "3")).thenReturn(null);
    try {
        when(mock.threeArgumentMethod(1, eq("2"), "3")).thenReturn(null);
        fail();
    } catch (InvalidUseOfMatchersException e) {
        assertThat(e.getMessage())
                  .contains("3 matchers expected")
                  .contains("1 recorded");
    }
}
 
Example #15
Source File: TestNGShouldFailWhenMockitoListenerFailsTest.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void report_failure_on_incorrect_stubbing_syntax_with_matchers_in_configuration_methods() throws Exception {
    TestNG testNG = new_TestNG_with_failure_recorder_for(FailingOnPurposeBecauseWrongStubbingSyntaxInConfigurationMethod.class);

    testNG.run();

    assertTrue(testNG.hasFailure());
    assertThat(failureRecorder.lastThrowable()).isInstanceOf(InvalidUseOfMatchersException.class);
}
 
Example #16
Source File: TestNGShouldFailWhenMockitoListenerFailsTest.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void report_failure_on_incorrect_stubbing_syntax_with_matchers_in_test_methods() throws Exception {
    TestNG testNG = new_TestNG_with_failure_recorder_for(FailingOnPurposeBecauseIncorrectStubbingSyntax.class);

    testNG.run();

    assertTrue(testNG.hasFailure());
    assertThat(failureRecorder.lastThrowable()).isInstanceOf(InvalidUseOfMatchersException.class);
}
 
Example #17
Source File: DetectingMisusedMatchersTest.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void should_fail_fast_when_argument_matchers_are_abused() {
    misplaced_anyObject_argument_matcher();
    try {
        mock(IMethods.class);
        fail();
    } catch (InvalidUseOfMatchersException e) {
        assertContains("Misplaced argument matcher", e.getMessage());
    }
}
 
Example #18
Source File: ClickableStackTracesWhenFrameworkMisusedTest.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void shouldPointOutMisplacedMatcher() {
    misplacedArgumentMatcherHere();
    try {
        verify(mock).simpleMethod();
        fail();
    } catch (InvalidUseOfMatchersException e) {
        assertContains("-> at ", e.getMessage());
        assertContains("misplacedArgumentMatcherHere(", e.getMessage());
    }
}
 
Example #19
Source File: ClickableStackTracesWhenFrameworkMisusedTest.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void shouldPointOutMisplacedMatcher() {
    misplacedArgumentMatcherHere();
    try {
        verify(mock).simpleMethod();
        fail();
    } catch (InvalidUseOfMatchersException e) {
        assertContains("-> at ", e.getMessage());
        assertContains("misplacedArgumentMatcherHere(", e.getMessage());
    }
}
 
Example #20
Source File: DetectingMisusedMatchersTest.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void shouldFailFastWhenArgumentMatchersAbused() {
    misplacedArgumentMatcher();
    try {
        mock(IMethods.class);
        fail();
    } catch (InvalidUseOfMatchersException e) {
        assertContains("Misplaced argument matcher", e.getMessage());
    }
}
 
Example #21
Source File: ExplicitFrameworkValidationTest.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void shouldDetectMisplacedArgumentMatcher() {
    anyObject();
    try {
        Mockito.validateMockitoUsage();
        fail();
    } catch (InvalidUseOfMatchersException e) {}
}
 
Example #22
Source File: InvalidUseOfMatchersTest.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void shouldDetectStupidUseOfMatchersWhenVerifying() {
    mock.oneArg(true);
    eq("that's the stupid way");
    eq("of using matchers");
    try {
        Mockito.verify(mock).oneArg(true);
        fail();
    } catch (InvalidUseOfMatchersException e) {}
}
 
Example #23
Source File: InvalidUseOfMatchersTest.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void shouldDetectWrongNumberOfMatchersWhenStubbing() {
    Mockito.when(mock.threeArgumentMethod(1, "2", "3")).thenReturn(null);
    try {
        Mockito.when(mock.threeArgumentMethod(1, eq("2"), "3")).thenReturn(null);
        fail();
    } catch (InvalidUseOfMatchersException e) {}
}
 
Example #24
Source File: PersonIrsDataVerifierTest.java    From mockito-cookbook with Apache License 2.0 4 votes vote down vote up
@Test(expected = InvalidUseOfMatchersException.class)
public void should_throw_exception_when_improperly_using_matchers() {
    // expect
    given(irsDataFetcher.isIrsApplicable(any(Person.class), "Warsaw")).willReturn(true);
}
 
Example #25
Source File: PersonIrsDataVerifierTestNgTest.java    From mockito-cookbook with Apache License 2.0 4 votes vote down vote up
@Test(expectedExceptions = InvalidUseOfMatchersException.class)
public void should_throw_exception_when_improperly_using_matchers() {
    // expect
    given(irsDataFetcher.isIrsApplicable(any(Person.class), "Warsaw")).willReturn(true);
}
 
Example #26
Source File: SSOSessionHandlerTest.java    From graviteeio-access-management with Apache License 2.0 4 votes vote down vote up
@Test
public void shouldInvoke_differentClient_differentIdp() throws Exception {
    User user = new User();
    user.setId("user-id");
    user.setClient("test-client");
    user.setSource("idp-1");

    Client client = new Client();
    client.setId("client-id");
    client.setClientId("test-client");

    Client requestedClient = new Client();
    requestedClient.setId("client-requested-id");
    requestedClient.setClientId("requested-client");
    requestedClient.setIdentities(Collections.singleton("idp-2"));

    when(userManager.get(user.getId())).thenReturn(Maybe.just(user));
    when(clientSyncService.findById(anyString())).thenReturn(Maybe.empty());
    when(clientSyncService.findByClientId(anyString())).thenAnswer(
            invocation -> {
                String argument = invocation.getArgument(0);
                if (argument.equals("test-client")) {
                    return Maybe.just(client);
                } else if (argument.equals("requested-client")) {
                    return Maybe.just(requestedClient);
                }
                throw new InvalidUseOfMatchersException(
                        String.format("Argument %s does not match", argument)
                );
            }
    );

    router.route().order(-1).handler(routingContext -> {
        routingContext.setUser(new io.vertx.reactivex.ext.auth.User(new io.gravitee.am.gateway.handler.common.vertx.web.auth.user.User(user)));
        routingContext.next();
    });

    testRequest(
            HttpMethod.GET,
            "/login?client_id=requested-client",
            HttpStatusCode.FORBIDDEN_403, "Forbidden");
}
 
Example #27
Source File: FailingOnPurposeBecauseIncorrectStubbingSyntax.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
@Test(expectedExceptions = InvalidUseOfMatchersException.class)
public void incorrect_stubbing_syntax_in_test() throws Exception {
    mock(PrintStream.class);
    anyString();
    anySet();
}
 
Example #28
Source File: PersonIrsDataVerifierTestNgTest.java    From mockito-cookbook with Apache License 2.0 4 votes vote down vote up
@Test(expectedExceptions = InvalidUseOfMatchersException.class)
public void should_throw_exception_when_improperly_using_matchers() {
    // expect
    given(irsDataFetcher.isIrsApplicable(any(Person.class), "Warsaw")).willReturn(true);
}
 
Example #29
Source File: SSOSessionHandlerTest.java    From graviteeio-access-management with Apache License 2.0 4 votes vote down vote up
@Test
public void shouldInvoke_differentClient_sameIdp() throws Exception {
    User user = new User();
    user.setId("user-id");
    user.setClient("test-client");
    user.setSource("idp-1");

    Client client = new Client();
    client.setId("client-id");
    client.setClientId("test-client");

    Client requestedClient = new Client();
    requestedClient.setId("client-requested-id");
    requestedClient.setClientId("requested-client");
    requestedClient.setIdentities(Collections.singleton("idp-1"));

    when(userManager.get(user.getId())).thenReturn(Maybe.just(user));
    when(clientSyncService.findById(anyString())).thenReturn(Maybe.empty()).thenReturn(Maybe.empty());
    when(clientSyncService.findByClientId(anyString())).thenAnswer(
            invocation -> {
                String argument = invocation.getArgument(0);
                if (argument.equals("test-client")) {
                    return Maybe.just(client);
                } else if (argument.equals("requested-client")) {
                    return Maybe.just(requestedClient);
                }
                throw new InvalidUseOfMatchersException(
                        String.format("Argument %s does not match", argument)
                );
            }
    );

    router.route().order(-1).handler(routingContext -> {
        routingContext.setUser(new io.vertx.reactivex.ext.auth.User(new io.gravitee.am.gateway.handler.common.vertx.web.auth.user.User(user)));
        routingContext.next();
    });

    testRequest(
            HttpMethod.GET,
            "/login?client_id=requested-client",
            HttpStatusCode.OK_200, "OK");
}
 
Example #30
Source File: ArgumentMatcherStorageImpl.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
private void assertState(boolean toAssert, String message) {
    if (!toAssert) {
        matcherStack.clear();
        throw new InvalidUseOfMatchersException(message);
    }
}