下面列出了怎么用org.mockito.invocation.Invocation的API类实例代码及写法,或者点击链接到github查看源代码。
@Test
public void should_get_results_for_methods_stub_only() throws Throwable {
invocationContainerImplStubOnly.setInvocationForPotentialStubbing(new InvocationMatcher(simpleMethod));
invocationContainerImplStubOnly.addAnswer(new Returns("simpleMethod"));
Invocation differentMethod = new InvocationBuilder().differentMethod().toInvocation();
invocationContainerImplStubOnly.setInvocationForPotentialStubbing(new InvocationMatcher(differentMethod));
invocationContainerImplStubOnly.addAnswer(new ThrowsException(new MyException()));
assertEquals("simpleMethod", invocationContainerImplStubOnly.answerTo(simpleMethod));
try {
invocationContainerImplStubOnly.answerTo(differentMethod);
fail();
} catch (MyException e) {}
}
public void verify(VerificationData verificationData) {
List<Invocation> invocations = verificationData.getAllInvocations();
InvocationMatcher invocationMatcher = verificationData.getWanted();
if (invocations == null || invocations.isEmpty()) {
throw new MockitoException(
"\nNo interactions with "
+ invocationMatcher.getInvocation().getMock()
+ " mock so far");
}
Invocation invocation = invocations.get(invocations.size() - 1);
if (!invocationMatcher.matches(invocation)) {
throw new MockitoException("\nWanted but not invoked:\n" + invocationMatcher);
}
}
@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());
}
@Test
//see issue 331
public void valid_handle_result_is_permitted() throws Throwable {
//given:
MockCreationSettings settings = (MockCreationSettings) new MockSettingsImpl().defaultAnswer(new Returns(123));
InternalMockHandler handler = new MockHandlerFactory().create(settings);
mock.intReturningMethod();
Invocation invocation = super.getLastInvocation();
//when:
Object result = handler.handle(invocation);
//then
assertEquals(123, result);
}
@Test
public void shouldMarkInvocationsAsVerifiedInOrder() {
//given
InOrderContextImpl context = new InOrderContextImpl();
InvocationMarker marker = new InvocationMarker();
Invocation i = new InvocationBuilder().toInvocation();
InvocationMatcher im = new InvocationBuilder().toInvocationMatcher();
assertFalse(context.isVerified(i));
assertFalse(i.isVerified());
//when
marker.markVerifiedInOrder(Arrays.asList(i), im, context);
//then
assertTrue(context.isVerified(i));
assertTrue(i.isVerified());
}
@Test
public void should_capture_varargs_as_vararg() throws Exception {
//given
mock.mixedVarargs(1, "a", "b");
Invocation invocation = getLastInvocation();
CapturingMatcher m = new CapturingMatcher();
InvocationMatcher invocationMatcher = new InvocationMatcher(invocation, (List) asList(new Equals(1), new LocalizedMatcher(m)));
//when
invocationMatcher.captureArgumentsFrom(invocation);
//then
Assertions.assertThat(m.getAllValues()).containsExactly("a", "b");
}
private static Object[] getInvocationArguments(Invocation invocation, InvocationArgumentsAdapter... argumentAdapters) {
Object[] arguments = invocation.getArguments();
for (InvocationArgumentsAdapter adapter : argumentAdapters) {
arguments = adapter.adaptArguments(arguments);
}
return arguments;
}
/**
* Verify the same invocations have been applied to two mocks. This is generally not
* the preferred way test with mockito and should be avoided if possible.
* @param expected the mock containing expected invocations
* @param actual the mock containing actual invocations
* @param argumentAdapters adapters that can be used to change argument values before they are compared
*/
public static <T> void verifySameInvocations(T expected, T actual, InvocationArgumentsAdapter... argumentAdapters) {
List<Invocation> expectedInvocations =
((InvocationContainerImpl) MockUtil.getMockHandler(expected).getInvocationContainer()).getInvocations();
List<Invocation> actualInvocations =
((InvocationContainerImpl) MockUtil.getMockHandler(actual).getInvocationContainer()).getInvocations();
verifySameInvocations(expectedInvocations, actualInvocations, argumentAdapters);
}
private static void verifySameInvocations(List<Invocation> expectedInvocations, List<Invocation> actualInvocations,
InvocationArgumentsAdapter... argumentAdapters) {
assertThat(expectedInvocations.size(), is(equalTo(actualInvocations.size())));
for (int i = 0; i < expectedInvocations.size(); i++) {
verifySameInvocation(expectedInvocations.get(i), actualInvocations.get(i), argumentAdapters);
}
}
@Test
public void shouldReturnCastedArgumentAt(){
//given
int argument = 42;
Invocation invocationOnInterface = new InvocationBuilder().method("twoArgumentMethod").
argTypes(int.class, int.class).args(1, argument).toInvocation();
//when
int secondArgument = invocationOnInterface.getArgumentAt(1, int.class);
//then
assertTrue(secondArgument == argument);
}
private static Object[] getInvocationArguments(Invocation invocation, InvocationArgumentsAdapter... argumentAdapters) {
Object[] arguments = invocation.getArguments();
for (InvocationArgumentsAdapter adapter : argumentAdapters) {
arguments = adapter.adaptArguments(arguments);
}
return arguments;
}
@Test
public void should_not_return_to_string_method() throws Exception {
Invocation toString = new InvocationBuilder().method("toString").toInvocation();
Invocation simpleMethod = new InvocationBuilder().simpleMethod().toInvocation();
invocations.add(toString);
invocations.add(simpleMethod);
assertTrue(invocations.getAll().contains(simpleMethod));
assertFalse(invocations.getAll().contains(toString));
}
public void verifyInOrder(VerificationDataInOrder data) {
List<Invocation> allInvocations = data.getAllInvocations();
InvocationMatcher wanted = data.getWanted();
if (wantedCount > 0) {
MissingInvocationInOrderChecker missingInvocation = new MissingInvocationInOrderChecker();
missingInvocation.check(allInvocations, wanted, this, data.getOrderingContext());
}
NumberOfInvocationsInOrderChecker numberOfCalls = new NumberOfInvocationsInOrderChecker();
numberOfCalls.check(allInvocations, wanted, wantedCount, data.getOrderingContext());
}
public List<Invocation> getAll() {
List<Invocation> copiedList;
synchronized (invocations) {
copiedList = new LinkedList<Invocation>(invocations) ;
}
return ListUtil.filter(copiedList, new RemoveToString());
}
@Test
public void shouldReportWithLastInvocationStackTrace() throws Exception {
Invocation first = new InvocationBuilder().toInvocation();
Invocation second = new InvocationBuilder().toInvocation();
finderStub.actualToReturn.addAll(asList(first, second));
checker.check(invocations, wanted, 100);
assertSame(second.getLocation(), reporterStub.location);
}
void verifyClose(int numExpected) throws NoSuchMethodException {
// Producer close is invoked in a separate thread. Must wait for the thread to get scheduled and call close
Method method = Producer.class.getMethod("close", long.class, TimeUnit.class);
PollUtils.poll(() -> {
Collection<Invocation> invocations = mockingDetails(_mockProducer).getInvocations();
long count = invocations.stream().filter(invocation -> invocation.getMethod().equals(method)).count();
return count == numExpected;
}, 1000, 10000);
verify(_mockProducer, times(numExpected)).close(anyLong(), any(TimeUnit.class));
Assert.assertEquals(_numShutdownProducerCalls, numExpected);
_numShutdownProducerCalls = 0;
}
@Test
public void shouldMatchAnyVarargEvenIfOneOfTheArgsIsNull() {
//given
mock.mixedVarargs(null, null, "2");
Invocation invocation = getLastInvocation();
InvocationMatcher invocationMatcher = new InvocationMatcher(invocation, (List) asList(new Equals(null), AnyVararg.ANY_VARARG));
//when
boolean match = comparator.argumentsMatch(invocationMatcher, invocation);
//then
assertTrue(match);
}
public void noMoreInteractionsWantedInOrder(Invocation undesired) {
throw new VerificationInOrderFailure(join(
"No interactions wanted here:",
new LocationImpl(),
"But found this interaction:",
undesired.getLocation(),
""
));
}
@Test
public void shouldKnowWhenArgsDifferent() {
//given
Invocation invocation = new InvocationBuilder().args("1", 100).toInvocation();
InvocationMatcher invocationMatcher = new InvocationBuilder().args("100", 100).toInvocationMatcher();
//when
boolean match = comparator.argumentsMatch(invocationMatcher, invocation);
//then
assertFalse(match);
}
public void check(List<Invocation> invocations, InvocationMatcher wanted, int wantedCount) {
List<Invocation> chunk = finder.findAllMatchingUnverifiedChunks(invocations, wanted, orderingContext);
int actualCount = chunk.size();
if (wantedCount > actualCount) {
Location lastLocation = finder.getLastLocation(chunk);
reporter.tooLittleActualInvocationsInOrder(new AtLeastDiscrepancy(wantedCount, actualCount), wanted, lastLocation);
}
invocationMarker.markVerifiedInOrder(chunk, wanted, orderingContext);
}
@Test
public void shouldKnowWhenVarargsDifferent() {
//given
mock.varargs("1", "2");
Invocation invocation = getLastInvocation();
InvocationMatcher invocationMatcher = new InvocationMatcher(invocation, (List) asList(new Equals("100"), Any.ANY));
//when
boolean match = comparator.argumentsMatch(invocationMatcher, invocation);
//then
assertFalse(match);
}
@Test
public void shouldPrintUnstubbedInvocation() {
// given
InvocationMatcher unstubbedInvocation = new InvocationBuilder().differentMethod().toInvocationMatcher();
// when
WarningsFinder finder = new WarningsFinder(Arrays.<Invocation>asList(), Arrays.<InvocationMatcher>asList(unstubbedInvocation));
finder.find(listener);
// then
verify(listener, only()).foundUnstubbed(unstubbedInvocation);
}
public InvocationMatcher bindMatchers(ArgumentMatcherStorage argumentMatcherStorage, Invocation invocation) {
List<LocalizedMatcher> lastMatchers = argumentMatcherStorage.pullLocalizedMatchers();
validateMatchers(invocation, lastMatchers);
InvocationMatcher invocationWithMatchers = new InvocationMatcher(invocation, (List<Matcher>)(List) lastMatchers);
return invocationWithMatchers;
}
@Test
public void shouldKnowWhenArgumentsMatch() {
//given
Invocation invocation = new InvocationBuilder().args("1", 100).toInvocation();
InvocationMatcher invocationMatcher = new InvocationBuilder().args("1", 100).toInvocationMatcher();
//when
boolean match = comparator.argumentsMatch(invocationMatcher, invocation);
//then
assertTrue(match);
}
@Test
public void shouldScreamWhenCallingRealMethodOnInterface() throws Throwable {
//given
Invocation invocationOnInterface = new InvocationBuilder().toInvocation();
try {
//when
invocationOnInterface.callRealMethod();
//then
fail();
} catch(MockitoException e) {}
}
@Test
public void shouldAllowAnyVarargMatchEntireVararg() {
//given
mock.varargs("1", "2");
Invocation invocation = getLastInvocation();
InvocationMatcher invocationMatcher = new InvocationMatcher(invocation, (List) asList(AnyVararg.ANY_VARARG));
//when
boolean match = comparator.argumentsMatch(invocationMatcher, invocation);
//then
assertTrue(match);
}
@Test
public void shouldFindActualInvocations() throws Exception {
List<Invocation> actual = finder.findInvocations(invocations, new InvocationMatcher(simpleMethodInvocation));
assertThat(actual, hasExactlyInOrder(simpleMethodInvocation, simpleMethodInvocationTwo));
actual = finder.findInvocations(invocations, new InvocationMatcher(differentMethodInvocation));
assertThat(actual, hasExactlyInOrder(differentMethodInvocation));
}
@Before
public void setup() {
reporter = new Reporter();
finderStub = new InvocationsFinderStub();
checker = new NumberOfInvocationsInOrderChecker(finderStub, reporter);
wanted = new InvocationBuilder().toInvocationMatcher();
invocations = new LinkedList<Invocation>(asList(new InvocationBuilder().toInvocation()));
}
@Test
public void shouldNotCountDuplicatedInteractions() throws Exception {
mockOne.simpleMethod(100);
List<Invocation> invocations = finder.find(asList(mockOne, mockOne, mockOne));
assertEquals(1, invocations.size());
}
@Test
public void shouldNotMarkAsVerifiedWhenAssertionFailed() {
//given
Invocation invocation = new InvocationBuilder().toInvocation();
assertFalse(invocation.isVerified());
//when
try {
only.verify(new VerificationDataStub(new InvocationBuilder().toInvocationMatcher(), invocation));
fail();
} catch (MockitoAssertionError e) {}
//then
assertFalse(invocation.isVerified());
}