类org.mockito.exceptions.misusing.InvalidUseOfMatchersException源码实例Demo

下面列出了怎么用org.mockito.exceptions.misusing.InvalidUseOfMatchersException的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: OpenAs2App   文件: AS2MessageMDNTest.java
@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));
        }
    });
}
 
源代码2 项目: astor   文件: Reporter.java
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().",
            ""
            ));
}
 
源代码3 项目: astor   文件: MockHandlerTest.java
@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());
}
 
源代码4 项目: astor   文件: InvalidStateDetectionTest.java
@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);
}
 
源代码5 项目: astor   文件: DetectingMisusedMatchersTest.java
@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());
    }
}
 
源代码6 项目: astor   文件: MockHandlerImplTest.java
@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());
}
 
源代码7 项目: astor   文件: InvalidStateDetectionTest.java
@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);
}
 
源代码8 项目: astor   文件: Reporter.java
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."
    ));
}
 
源代码9 项目: astor   文件: InvalidUseOfMatchersTest.java
@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) {}
}
 
源代码10 项目: astor   文件: InvalidUseOfMatchersTest.java
@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) {}
}
 
源代码11 项目: astor   文件: ExplicitFrameworkValidationTest.java
@Test
public void shouldDetectMisplacedArgumentMatcher() {
    anyObject();
    try {
        Mockito.validateMockitoUsage();
        fail();
    } catch (InvalidUseOfMatchersException e) {}
}
 
源代码12 项目: astor   文件: DetectingMisusedMatchersTest.java
@Test
public void shouldFailFastWhenArgumentMatchersAbused() {
    misplacedArgumentMatcher();
    try {
        mock(IMethods.class);
        fail();
    } catch (InvalidUseOfMatchersException e) {
        assertContains("Misplaced argument matcher", e.getMessage());
    }
}
 
@Test
public void shouldPointOutMisplacedMatcher() {
    misplacedArgumentMatcherHere();
    try {
        verify(mock).simpleMethod();
        fail();
    } catch (InvalidUseOfMatchersException e) {
        assertContains("-> at ", e.getMessage());
        assertContains("misplacedArgumentMatcherHere(", e.getMessage());
    }
}
 
@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);
}
 
@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);
}
 
源代码16 项目: astor   文件: InvalidUseOfMatchersTest.java
@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");
    }
}
 
源代码17 项目: astor   文件: InvalidUseOfMatchersTest.java
@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();
    }
}
 
源代码18 项目: astor   文件: InvalidUseOfMatchersTest.java
@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(?)");
    }
}
 
源代码19 项目: astor   文件: InvalidUseOfMatchersTest.java
@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");
    }
}
 
源代码20 项目: astor   文件: InvalidUseOfMatchersTest.java
@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");
    }
}
 
源代码21 项目: astor   文件: ExplicitFrameworkValidationTest.java
@Test
public void shouldDetectMisplacedArgumentMatcher() {
    anyObject();
    try {
        Mockito.validateMockitoUsage();
        fail();
    } catch (InvalidUseOfMatchersException e) {}
}
 
源代码22 项目: astor   文件: DetectingMisusedMatchersTest.java
@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());
    }
}
 
@Test
public void shouldPointOutMisplacedMatcher() {
    misplacedArgumentMatcherHere();
    try {
        verify(mock).simpleMethod();
        fail();
    } catch (InvalidUseOfMatchersException e) {
        assertContains("-> at ", e.getMessage());
        assertContains("misplacedArgumentMatcherHere(", e.getMessage());
    }
}
 
@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");
}
 
@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");
}
 
@Test(expectedExceptions = InvalidUseOfMatchersException.class)
public void should_throw_exception_when_improperly_using_matchers() {
    // expect
    given(irsDataFetcher.isIrsApplicable(any(Person.class), "Warsaw")).willReturn(true);
}
 
@Test(expected = InvalidUseOfMatchersException.class)
public void should_throw_exception_when_improperly_using_matchers() {
    // expect
    given(irsDataFetcher.isIrsApplicable(any(Person.class), "Warsaw")).willReturn(true);
}
 
@Test(expectedExceptions = InvalidUseOfMatchersException.class)
public void should_throw_exception_when_improperly_using_matchers() {
    // expect
    given(irsDataFetcher.isIrsApplicable(any(Person.class), "Warsaw")).willReturn(true);
}
 
@Test(expected = InvalidUseOfMatchersException.class)
public void should_throw_exception_when_improperly_using_matchers() {
    // expect
    given(irsDataFetcher.isIrsApplicable(any(Person.class), "Warsaw")).willReturn(true);
}
 
源代码30 项目: astor   文件: ArgumentMatcherStorageImpl.java
private void assertState(boolean toAssert, String message) {
    if (!toAssert) {
        matcherStack.clear();
        throw new InvalidUseOfMatchersException(message);
    }
}
 
 类所在包
 同包方法