Java 类org.mockito.invocation.Invocation 实例源码

项目:mockito-cglib    文件:MethodInterceptorFilter.java   
public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy)
        throws Throwable {
    if (objectMethodsGuru.isEqualsMethod(method)) {
        return proxy == args[0];
    } else if (objectMethodsGuru.isHashCodeMethod(method)) {
        return hashCodeForMock(proxy);
    } else if (acrossJVMSerializationFeature.isWriteReplace(method)) {
        return acrossJVMSerializationFeature.writeReplace(proxy);
    }

    MockitoMethodProxy mockitoMethodProxy = createMockitoMethodProxy(methodProxy);
    new CGLIBHacker().setMockitoNamingPolicy(methodProxy);

    MockitoMethod mockitoMethod = createMockitoMethod(method);

    CleanTraceRealMethod realMethod = new CleanTraceRealMethod(mockitoMethodProxy);
    Invocation invocation = new InvocationImpl(proxy, mockitoMethod, args, SequenceNumber.next(), realMethod);
    return handler.handle(invocation);
}
项目:che    文件:ConcurrentCompositeLineConsumerTest.java   
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);
  }
}
项目:astor    文件:InvocationMatcher.java   
/**
 * similar means the same method name, same mock, unverified 
 * and: if arguments are the same cannot be overloaded
 */
public boolean hasSimilarMethod(Invocation candidate) {
    String wantedMethodName = getMethod().getName();
    String currentMethodName = candidate.getMethod().getName();

    final boolean methodNameEquals = wantedMethodName.equals(currentMethodName);
    final boolean isUnverified = !candidate.isVerified();
    final boolean mockIsTheSame = getInvocation().getMock() == candidate.getMock();
    final boolean methodEquals = hasSameMethod(candidate);

    if (!methodNameEquals || !isUnverified || !mockIsTheSame) {
        return false;
    }

    final boolean overloadedButSameArgs = !methodEquals && safelyArgumentsMatch(candidate.getArguments());

    return !overloadedButSameArgs;
}
项目:astor    文件:InvocationMatcher.java   
public boolean hasSameMethod(Invocation candidate) {
    //not using method.equals() for 1 good reason:
    //sometimes java generates forwarding methods when generics are in play see JavaGenericsForwardingMethodsTest
    Method m1 = invocation.getMethod();
    Method m2 = candidate.getMethod();

    if (m1.getName() != null && m1.getName().equals(m2.getName())) {
        /* Avoid unnecessary cloning */
        Class[] params1 = m1.getParameterTypes();
        Class[] params2 = m2.getParameterTypes();
        if (params1.length == params2.length) {
            for (int i = 0; i < params1.length; i++) {
            if (params1[i] != params2[i])
                return false;
            }
            return true;
        }
    }
    return false;
}
项目:astor    文件:InvocationMatcher.java   
public void captureArgumentsFrom(Invocation invocation) {
    for (int position = 0; position < matchers.size(); position++) {
        Matcher m = matchers.get(position);
        if (m instanceof CapturesArguments && invocation.getRawArguments().length > position) {
            //TODO SF - this whole lot can be moved captureFrom implementation
            if(isVariableArgument(invocation, position) && isVarargMatcher(m)) {
                Object array = invocation.getRawArguments()[position];
                for (int i = 0; i < Array.getLength(array); i++) {
                    ((CapturesArguments) m).captureFrom(Array.get(array, i));
                }
                //since we've captured all varargs already, it does not make sense to process other matchers.
                return;
            } else {
                ((CapturesArguments) m).captureFrom(invocation.getRawArguments()[position]);
            }
        }
    }
}
项目:astor    文件:InvocationContainerImplStubbingTest.java   
@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) {}
}
项目:astor    文件:InvocationsFinder.java   
public Invocation findSimilarInvocation(List<Invocation> invocations, InvocationMatcher wanted) {
    Invocation firstSimilar = null;
    for (Invocation invocation : invocations) {
        if (!wanted.hasSimilarMethod(invocation)) {
            continue;
        }
        if (firstSimilar == null) {
            firstSimilar = invocation;
        }
        if (wanted.hasSameMethod(invocation)) {
            return invocation;
        }
    }

    return firstSimilar;
}
项目:astor    文件:InvocationContainerImplStubbingTest.java   
@Test
public void should_get_results_for_methods() throws Throwable {
    invocationContainerImpl.setInvocationForPotentialStubbing(new InvocationMatcher(simpleMethod));
    invocationContainerImpl.addAnswer(new Returns("simpleMethod"));

    Invocation differentMethod = new InvocationBuilder().differentMethod().toInvocation();
    invocationContainerImpl.setInvocationForPotentialStubbing(new InvocationMatcher(differentMethod));
    invocationContainerImpl.addAnswer(new ThrowsException(new MyException()));

    assertEquals("simpleMethod", invocationContainerImpl.answerTo(simpleMethod));

    try {
        invocationContainerImpl.answerTo(differentMethod);
        fail();
    } catch (MyException e) {}
}
项目:astor    文件:InvocationMarkerTest.java   
@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());
}
项目:spring4-understanding    文件:MockitoUtils.java   
private static void verifySameInvocation(Invocation expectedInvocation, Invocation actualInvocation, InvocationArgumentsAdapter... argumentAdapters) {
    System.out.println(expectedInvocation);
    System.out.println(actualInvocation);
    assertThat(expectedInvocation.getMethod(), is(equalTo(actualInvocation.getMethod())));
    Object[] expectedArguments = getInvocationArguments(expectedInvocation, argumentAdapters);
    Object[] actualArguments = getInvocationArguments(actualInvocation, argumentAdapters);
    assertThat(expectedArguments, is(equalTo(actualArguments)));
}
项目:spring4-understanding    文件:MockitoUtils.java   
private static Object[] getInvocationArguments(Invocation invocation, InvocationArgumentsAdapter... argumentAdapters) {
    Object[] arguments = invocation.getArguments();
    for (InvocationArgumentsAdapter adapter : argumentAdapters) {
        arguments = adapter.adaptArguments(arguments);
    }
    return arguments;
}
项目:powermock    文件:PowerMockMatchersBinder.java   
public InvocationMatcher bindMatchers(ArgumentMatcherStorage argumentMatcherStorage, final Invocation invocation) {
    List<LocalizedMatcher> lastMatchers = argumentMatcherStorage.pullLocalizedMatchers();
    validateMatchers(invocation, lastMatchers);

    final InvocationMatcher invocationWithMatchers = new InvocationMatcher(invocation, (List<Matcher>)(List) lastMatchers) {
        @Override
        public String toString() {
            return invocation.toString();
        }
    };
    return invocationWithMatchers;
}
项目:powermock    文件:PowerMockMatchersBinder.java   
private void validateMatchers(Invocation invocation, List<LocalizedMatcher> lastMatchers) {
    if (!lastMatchers.isEmpty()) {
        int recordedMatchersSize = lastMatchers.size();
        int expectedMatchersSize = invocation.getArguments().length;
        if (expectedMatchersSize != recordedMatchersSize) {
            new Reporter().invalidUseOfMatchers(expectedMatchersSize, lastMatchers);
        }
    }
}
项目:mockito-cglib    文件:InvocationBuilder.java   
/**
 * Build the invocation
 *
 * If the method was not specified, use IMethods methods.
 *
 * @return invocation
 */
public Invocation toInvocation() {
    if (method == null) {
        if (argTypes == null) {
            argTypes = new LinkedList<Class<?>>();
            for (Object arg : args) {
                if (arg == null) {
                    argTypes.add(Object.class);
                } else {
                    argTypes.add(arg.getClass());
                }
            }
        }

        try {
            method = MethodsImpl.class.getMethod(methodName, argTypes.toArray(new Class[argTypes.size()]));
        } catch (Exception e) {
            throw new RuntimeException("builder only creates invocations of IMethods interface", e);
        }
    }

    Invocation i = new InvocationImpl(mock, new SerializableMethod(method), args, sequenceNumber, null);
    if (verified) {
        i.markVerified();
    }
    return i;
}
项目:l10n-maven-plugin    文件:ValidateMojoTest.java   
@Test
public void allConfigurationGettersShouldBeCalled() {
  plugin = new ValidateMojo(configuration);

  List<Method> invokedMethods = new ArrayList<Method>();
  for (Invocation invocation : mockingDetails(configuration).getInvocations()) {
    invokedMethods.add(invocation.getMethod());
  }

  for (Method method : L10nValidationConfiguration.class.getDeclaredMethods()) {
    if (method.getName().startsWith("get")) {
      assertThat("A getter was not called", invokedMethods, hasItem(method));
    }
  }
}
项目:astor    文件:InvocationsFinderTest.java   
@Test
public void shouldReturnAllChunksWhenWantedCountDoesntMatch() throws Exception {
    Invocation simpleMethodInvocationThree = new InvocationBuilder().mock(mock).toInvocation();
    invocations.add(simpleMethodInvocationThree);

    List<Invocation> chunk = finder.findMatchingChunk(invocations, new InvocationMatcher(simpleMethodInvocation), 1, context);
    assertThat(chunk, hasExactlyInOrder(simpleMethodInvocation, simpleMethodInvocationTwo, simpleMethodInvocationThree));
}
项目:astor    文件:ArgumentsComparatorTest.java   
@Test
public void shouldKnowWhenVarargsMatch() {
    //given
    mock.varargs("1", "2", "3");
    Invocation invocation = getLastInvocation();
    InvocationMatcher invocationMatcher = new InvocationMatcher(invocation, (List) asList(new Equals("1"), Any.ANY, new InstanceOf(String.class)));

    //when
    boolean match = comparator.argumentsMatch(invocationMatcher, invocation);

    //then
    assertTrue(match);
}
项目:astor    文件:InvocationMatcherTest.java   
@Test  // like using several time the captor in the vararg
public void should_capture_arguments_when_args_count_does_NOT_match() throws Exception {
    //given
    mock.varargs();
    Invocation invocation = getLastInvocation();

    //when
    InvocationMatcher invocationMatcher = new InvocationMatcher(invocation, (List) asList(new LocalizedMatcher(AnyVararg.ANY_VARARG)));

    //then
    invocationMatcher.captureArgumentsFrom(invocation);
}
项目:astor    文件:SmartPrinter.java   
public SmartPrinter(InvocationMatcher wanted, Invocation actual, Integer ... indexesOfMatchersToBeDescribedWithExtraTypeInfo) {
    PrintSettings printSettings = new PrintSettings();
    printSettings.setMultiline(wanted.toString().contains("\n") || actual.toString().contains("\n"));
    printSettings.setMatchersToBeDescribedWithExtraTypeInfo(indexesOfMatchersToBeDescribedWithExtraTypeInfo);

    this.wanted = printSettings.print(wanted);
    this.actual = printSettings.print(actual);
}
项目:astor    文件:MockHandlerFactoryTest.java   
@Test
//see issue 331
public void handle_result_must_not_be_null_for_primitives() throws Throwable {
    //given:
    MockCreationSettings settings = (MockCreationSettings) new MockSettingsImpl().defaultAnswer(new Returns(null));
    InternalMockHandler handler = new MockHandlerFactory().create(settings);

    mock.intReturningMethod();
    Invocation invocation = super.getLastInvocation();

    //when:
    Object result = handler.handle(invocation);

    //then null value is not a valid result for a primitive
    assertNotNull(result);
    assertEquals(0, result);
}
项目:astor    文件:InvocationMatcherTest.java   
@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");
}
项目:astor    文件:TestBase.java   
protected static Invocation invocationOf(Class<?> type, String methodName, Object ... args) throws NoSuchMethodException {
    Class[] types = new Class[args.length];
    for (int i = 0; i < args.length; i++) {
        types[i] = args[i].getClass();
    }
    return new InvocationImpl(mock(type), new SerializableMethod(type.getMethod(methodName,
            types)), args, 1, null);
}
项目:astor    文件:ArgumentsComparator.java   
private boolean varArgsMatch(InvocationMatcher invocationMatcher, Invocation actual) {
    if (!actual.getMethod().isVarArgs()) {
        //if the method is not vararg forget about it
        return false;
    }

    //we must use raw arguments, not arguments...
    Object[] rawArgs = actual.getRawArguments();
    List<Matcher> matchers = invocationMatcher.getMatchers();

    if (rawArgs.length != matchers.size()) {
        return false;
    }

    for (int i = 0; i < rawArgs.length; i++) {
        Matcher m = matchers.get(i);
        //it's a vararg because it's the last array in the arg list
        if (rawArgs[i] != null && rawArgs[i].getClass().isArray() && i == rawArgs.length-1) {
            Matcher actualMatcher;
            //this is necessary as the framework often decorates matchers
            if (m instanceof MatcherDecorator) {
                actualMatcher = ((MatcherDecorator)m).getActualMatcher();
            } else {
                actualMatcher = m;
            }
            //this is very important to only allow VarargMatchers here. If you're not sure why remove it and run all tests.
            if (!(actualMatcher instanceof VarargMatcher) || !actualMatcher.matches(rawArgs[i])) {
                return false;
            }
        //it's not a vararg (i.e. some ordinary argument before varargs), just do the ordinary check
        } else if (!m.matches(rawArgs[i])){
            return false;
        }
    }

    return true;
}
项目:astor    文件:MatchersBinder.java   
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;
}
项目:astor    文件:MatchersBinder.java   
private void validateMatchers(Invocation invocation, List<LocalizedMatcher> lastMatchers) {
    if (!lastMatchers.isEmpty()) {
        int recordedMatchersSize = lastMatchers.size();
        int expectedMatchersSize = invocation.getArguments().length;
        if (expectedMatchersSize != recordedMatchersSize) {
            new Reporter().invalidUseOfMatchers(expectedMatchersSize, lastMatchers);
        }
    }
}
项目:astor    文件:NumberOfInvocationsInOrderCheckerTest.java   
@Test
public void shouldReportTooLittleInvocations() throws Exception {
    Invocation first = new InvocationBuilder().toInvocation();
    Invocation second = new InvocationBuilder().toInvocation();
    finderStub.validMatchingChunkToReturn.addAll(asList(first, second)); 

    try {
        checker.check(invocations, wanted, 4, context);
        fail();
    } catch (VerificationInOrderFailure e) {
        assertContains("Wanted 4 times", e.getMessage());
        assertContains("But was 2 times", e.getMessage());
    }
}
项目:astor    文件:ArgumentsComparatorTest.java   
@Test
public void shouldNotAllowAnyObjectWithMixedVarargs() {
    //given
    mock.mixedVarargs(1, "1", "2");
    Invocation invocation = getLastInvocation();
    InvocationMatcher invocationMatcher = new InvocationMatcher(invocation, (List) asList(new Equals(1)));

    //when
    boolean match = comparator.argumentsMatch(invocationMatcher, invocation);

    //then
    assertFalse(match);
}
项目:astor    文件:InvocationMatcher.java   
public static List<InvocationMatcher> createFrom(List<Invocation> invocations) {
    LinkedList<InvocationMatcher> out = new LinkedList<InvocationMatcher>();

    for (Invocation i : invocations) {
        out.add(new InvocationMatcher(i));
    }

    return out;
}
项目:astor    文件:NumberOfInvocationsCheckerTest.java   
@Before
public void setup() {
    reporterStub = new ReporterStub();
    finderStub = new InvocationsFinderStub();
    checker = new NumberOfInvocationsChecker(reporterStub, finderStub);

    wanted = new InvocationBuilder().toInvocationMatcher();
    invocations = new LinkedList<Invocation>(asList(new InvocationBuilder().toInvocation()));
}
项目:astor    文件:NumberOfInvocationsCheckerTest.java   
@Test
public void shouldMarkInvocationsAsVerified() throws Exception {
    Invocation invocation = new InvocationBuilder().toInvocation();
    finderStub.actualToReturn.add(invocation);
    assertFalse(invocation.isVerified());

    checker.check(invocations, wanted, 1);

    assertTrue(invocation.isVerified());
}
项目:astor    文件:ArgumentsComparatorTest.java   
@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);
}
项目:astor    文件:InvocationsFinder.java   
private List<Invocation> removeVerifiedInOrder(List<Invocation> invocations, InOrderContext orderingContext) {
    List<Invocation> unverified = new LinkedList<Invocation>();
    for (Invocation i : invocations) {
        if (orderingContext.isVerified(i)) {
            unverified.clear();
        } else {
            unverified.add(i);
        }
    }
    return unverified;
}
项目:astor    文件:InvocationImplTest.java   
@Test
public void shouldKnowIfIsEqualTo() {
    Invocation equal =                  new InvocationBuilder().args(" ").mock("mock").toInvocation();
    Invocation nonEqual =               new InvocationBuilder().args("X").mock("mock").toInvocation();
    Invocation withNewStringInstance =  new InvocationBuilder().args(new String(" ")).mock("mock").toInvocation();

    assertFalse(invocation.equals(null));
    assertFalse(invocation.equals(""));
    assertTrue(invocation.equals(equal));
    assertFalse(invocation.equals(nonEqual));
    assertTrue(invocation.equals(withNewStringInstance));
}
项目:astor    文件:InvocationMarker.java   
public void markVerifiedInOrder(List<Invocation> chunk, CapturesArgumensFromInvocation wanted, InOrderContext context) {
    markVerified(chunk, wanted);

    for (Invocation i : chunk) {
        context.markVerified(i);
    }
}
项目:astor    文件:ScenarioPrinterTest.java   
@Test
public void shouldNotPrintInvocationsWhenSingleUnwanted() {
    //given
    Invocation unverified = new InvocationBuilder().differentMethod().toInvocation();

    //when
    String out = sp.print((List) asList(unverified));

    //then
    assertContains("Actually, above is the only interaction with this mock.", out);
}
项目:astor    文件:AnswersValidatorTest.java   
@Test
public void should_fail_when_calling_real_method_on_interface() throws Throwable {
    //given
    Invocation invocationOnInterface = new InvocationBuilder().method("simpleMethod").toInvocation();
    try {
        //when
        validator.validate(new CallsRealMethods(), invocationOnInterface);
        //then
        fail();
    } catch (MockitoException e) {}
}
项目:astor    文件:MockingDetailsTest.java   
@Test
public void testGetInvocations() {
    List<String> methodsInvoked = new ArrayList<String>() {{
        add("add");
        add("remove");
        add("clear");
    }};

    List<String> mockedList = (List<String>) mock(List.class);

    mockedList.add("one");
    mockedList.remove(0);
    mockedList.clear();

    MockingDetails mockingDetails = new MockitoCore().mockingDetails(mockedList);
    Collection<Invocation> invocations = mockingDetails.getInvocations();

    assertNotNull(invocations);
    assertEquals(invocations.size(),3);
    for (Invocation method : invocations) {
        assertTrue(methodsInvoked.contains(method.getMethod().getName()));
        if (method.getMethod().getName().equals("add")) {
            assertEquals(method.getArguments().length,1);
            assertEquals(method.getArguments()[0],"one");
        }
    }   
}
项目:astor    文件:AllInvocationsFinder.java   
/**
 * gets all invocations from mocks. Invocations are ordered earlier first. 
 * 
 * @param mocks mocks
 * @return invocations
 */
public List<Invocation> find(List<?> mocks) {
    Set<Invocation> invocationsInOrder = new TreeSet<Invocation>(new SequenceNumberComparator());
    for (Object mock : mocks) {
        InternalMockHandler<Object> handler = new MockUtil().getMockHandler(mock);
        List<Invocation> fromSingleMock = handler.getInvocationContainer().getInvocations();
        invocationsInOrder.addAll(fromSingleMock);
    }

    return new LinkedList<Invocation>(invocationsInOrder);
}
项目:astor    文件:MethodInfoTest.java   
@Test
public void shouldKnowValidThrowables() throws Exception {
    //when
    Invocation invocation = new InvocationBuilder().method("canThrowException").toInvocation();
    MethodInfo info = new MethodInfo(invocation);

    //then
    assertFalse(info.isValidException(new Exception()));
    assertTrue(info.isValidException(new CharacterCodingException()));
}
项目:astor    文件:InvocationImplTest.java   
@Test
public void shouldTransformArgumentsToMatchers() throws Exception {
    Invocation i = new InvocationBuilder().args("foo", new String[]{"bar"}).toInvocation();
    List matchers = ArgumentsProcessor.argumentsToMatchers(i.getArguments());

    assertEquals(2, matchers.size());
    assertEquals(Equals.class, matchers.get(0).getClass());
    assertEquals(ArrayEquals.class, matchers.get(1).getClass());
}