protected Statement withBefores(FrameworkMethod method, Object target, Statement statement) { this.target = target; // get new test listener and add it to the framework mockitoTestListener = listenerSupplier.get(); Mockito.framework().addListener(mockitoTestListener); // init annotated mocks before tests MockitoAnnotations.initMocks(target); return super.withBefores(method, target, statement); }
public DefaultMockitoSession(List<Object> testClassInstances, String name, Strictness strictness, MockitoLogger logger) { this.name = name; listener = new UniversalTestListener(strictness, logger); try { //So that the listener can capture mock creation events Mockito.framework().addListener(listener); } catch (RedundantListenerException e) { Reporter.unfinishedMockingSession(); } try { for (Object testClassInstance : testClassInstances) { MockitoAnnotations.initMocks(testClassInstance); } } catch (RuntimeException e) { //clean up in case 'initMocks' fails listener.setListenerDirty(); throw e; } }
@Override public void finishMocking(final Throwable failure) { //Cleaning up the state, we no longer need the listener hooked up //The listener implements MockCreationListener and at this point //we no longer need to listen on mock creation events. We are wrapping up the session Mockito.framework().removeListener(listener); //Emit test finished event so that validation such as strict stubbing can take place listener.testFinished(new TestFinishedEvent() { @Override public Throwable getFailure() { return failure; } @Override public String getTestName() { return name; } }); //Validate only when there is no test failure to avoid reporting multiple problems if (failure == null) { //Finally, validate user's misuse of Mockito framework. Mockito.validateMockitoUsage(); } } }
public void run(RunNotifier notifier) { //TODO need to be able to opt in for full stack trace instead of just relying on the stack trace filter UnnecessaryStubbingsReporter reporter = new UnnecessaryStubbingsReporter(); FailureDetector listener = new FailureDetector(); Mockito.framework().addListener(reporter); try { // add listener that detects test failures notifier.addListener(listener); runner.run(notifier); } finally { Mockito.framework().removeListener(reporter); } if (!filterRequested && listener.isSuccessful()) { //only report when: //1. if all tests from given test have ran (filter requested is false) // Otherwise we would report unnecessary stubs even if the user runs just single test from the class //2. tests are successful (we don't want to add an extra failure on top of any existing failure, to avoid confusion) reporter.validateUnusedStubs(testClass, notifier); } }
@Override public Object invoke(final Object proxy, final Method method, final Object[] rawArgs) throws Throwable { // args can be null if the method invoked has no arguments, but Mockito expects a non-null array Object[] args = rawArgs != null ? rawArgs : new Object[0]; if (isEqualsMethod(method)) { return proxy == args[0]; } else if (isHashCodeMethod(method)) { return System.identityHashCode(proxy); } return handler.handle(Mockito.framework().getInvocationFactory().createInvocation(proxy, withSettings().build(proxy.getClass().getSuperclass()), method, new RealMethodBehavior() { @Override public Object call() throws Throwable { return ProxyBuilder.callSuper(proxy, method, rawArgs); } }, args)); }
@Override public <T> T createMock(MockCreationSettings<T> settings, MockHandler handler) { Class<T> typeToMock = settings.getTypeToMock(); if (!typeToMock.equals(mockingInProgressClass.get()) || Modifier.isAbstract(typeToMock .getModifiers())) { return null; } Set<Class<?>> interfacesSet = settings.getExtraInterfaces(); InvocationHandlerAdapter handlerAdapter = new InvocationHandlerAdapter(handler); classTransformer.mockClass(MockFeatures.withMockFeatures(typeToMock, interfacesSet)); Instantiator instantiator = Mockito.framework().getPlugins().getDefaultPlugin (InstantiatorProvider2.class).getInstantiator(settings); T mock; try { mock = instantiator.newInstance(typeToMock); } catch (org.mockito.creation.instance.InstantiationException e) { throw new MockitoException("Unable to create mock instance of type '" + typeToMock .getSimpleName() + "'", e); } if (classToMarker.containsKey(typeToMock)) { throw new MockitoException(typeToMock + " is already mocked"); } classToMarker.put(typeToMock, mock); markerToHandler.put(mock, handlerAdapter); return mock; }
/** * Intercept a method call. Called <u>before</u> a method is called by the method entry hook. * * <p>This does the same as {@link #invoke(Object, Method, Object[])} but this handles methods * that got and entry hook. * * @param mock mocked object * @param method method that was called * @param rawArgs arguments to the method * @param superMethod The super method * * @return mocked result * @throws Throwable An exception if thrown */ Object interceptEntryHook(final Object mock, final Method method, final Object[] rawArgs, final SuperMethod superMethod) throws Throwable { // args can be null if the method invoked has no arguments, but Mockito expects a non-null Object[] args = rawArgs; if (rawArgs == null) { args = new Object[0]; } return handler.handle(Mockito.framework().getInvocationFactory().createInvocation(mock, withSettings().build(mock.getClass()), method, new RealMethodBehavior() { @Override public Object call() throws Throwable { return superMethod.invoke(); } }, args)); }
return handler.handle(Mockito.framework().getInvocationFactory().createInvocation(proxy, withSettings().build(proxy.getClass().getSuperclass()), method, new RealMethodBehavior() {
Instantiator instantiator = Mockito.framework().getPlugins() .getDefaultPlugin(InstantiatorProvider2.class).getInstantiator(settings);
/** * @param fluentBdd The JUnit {@link FluentBdd} {@link Rule} that this class will integrate with */ public FluentMockito(FluentBdd<TestResult> fluentBdd) { this(Mockito.framework(), MockitoJUnit.rule(), fluentBdd); }
private MockMaker doLoad(final ClassLoader loader, final String mockMakerClassName) throws ClassNotFoundException, InstantiationException, IllegalAccessException { if (mockMakerClassName == null) { return Mockito.framework().getPlugins().getDefaultPlugin(MockMaker.class); } else if ("mock-maker-inline".equals(mockMakerClassName)) { return Mockito.framework().getPlugins().getInlineMockMaker(); } else { Class<?> mockMakerClass = loader.loadClass(mockMakerClassName); Object mockMaker = mockMakerClass.newInstance(); return MockMaker.class.cast(mockMaker); } } }
Invocation createInvocation(final Object mock, final Method method, final MockCreationSettings settings, final Object... arguments) { final Callable realMethod = createRealMethod(mock, method, arguments); return Mockito.framework() .getInvocationFactory() .createInvocation(mock, settings, method, realMethod, arguments); }
@Override public void run(RunNotifier notifier) { if (shouldInitMocks) { //Allow Mockito to do its verification UnnecessaryStubbingsReporter reporter = new UnnecessaryStubbingsReporter(); FailureDetector listener = new FailureDetector(); Mockito.framework().addListener(reporter); try { notifier.addListener(listener); } finally { Mockito.framework().removeListener(reporter); } } super.run(notifier); }