How to use method of org.mockito.internal.MockitoCore class

Best Mockito code snippet using org.mockito.internal.MockitoCore.

Run Mockito automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

copy
1package org.powermock.api.extension.reporter;
2
3import org.powermock.core.reporter.MockingFrameworkReporter;
4
5/**
6 * The MockingFrameworkReporterFactory which create a new instance of MockingFrameworkReporter
7 * which is loaded by current context class loader.
8 */
9@SuppressWarnings("WeakerAccess")
10public class MockingFrameworkReporterFactoryImpl extends AbstractMockingFrameworkReporterFactory {
11
12    @Override
13    protected String getImplementerClassName() {
14        return "org.powermock.api.extension.reporter.MockingFrameworkReporterFactoryImpl$MockitoMockingFrameworkReporter";
15    }
16
17    @SuppressWarnings("unused")
18    private static class MockitoMockingFrameworkReporter implements MockingFrameworkReporter {
19// TODO: mockito2 reporter is internal now
20//        private org.mockito.internal.exceptions.Reporter mockitoReporter;
21//        private org.mockito.internal.MockitoCore mockitoCore;
22
23//        private org.mockito.internal.exceptions.Reporter getMockitoReporter(Object mockitoCore) {
24
25//            return Whitebox.getInternalState(mockitoCore, "reporter");
26//        }
27
28//        private void setMockitoReporter(org.mockito.internal.exceptions.Reporter reporter, org.mockito.internal.MockitoCore mockitoCore) {
29//            Whitebox.setInternalState(mockitoCore, "reporter", reporter);
30//        }
31
32        @Override
33        public void enable() {
34//            mockitoCore = getMockitoCoreForCurrentClassLoader();
35//            mockitoReporter = getMockitoReporter(mockitoCore);
36//
37//            PowerMockitoReporter powerMockitoReporter = new PowerMockitoReporter();
38//            setMockitoReporter(powerMockitoReporter, mockitoCore);
39        }
40
41//        private org.mockito.internal.MockitoCore getMockitoCoreForCurrentClassLoader() {
42//            ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
43//            try {
44//                return Whitebox.getInternalState(classLoader.loadClass("org.mockito.Mockito"), "MOCKITO_CORE");
45//            } catch (ClassNotFoundException e) {
46//                throw new RuntimeException(e);
47//            }
48//        }
49
50        @Override
51        public void disable() {
52//            setMockitoReporter(mockitoReporter, mockitoCore);
53        }
54    }
55
56    /**
57     * PowerMock reported for Mockito, which replace standard mockito message
58     * to specific message for cases when PowerMock is used.
59     */
60//    private static class PowerMockitoReporter extends org.mockito.internal.exceptions.Reporter {
61//
62//        public void missingMethodInvocation() {
63//            throw new org.mockito.exceptions.misusing.MissingMethodInvocationException(join(
64//                    "when() requires an argument which has to be 'a method call on a mock'.",
65//                    "For example:",
66//                    "    when(mock.getArticles()).thenReturn(articles);",
67//                    "Or 'a static method call on a prepared class`",
68//                    "For example:",
69//                    "    @PrepareForTest( { StaticService.class }) ",
70//                    "    TestClass{",
71//                    "       public void testMethod(){",
72//                    "           PowerMockito.mockStatic(StaticService.class);",
73//                    "           when(StaticService.say()).thenReturn(expected);",
74//                    "       }",
75//                    "    }",
76//                    "",
77//                    "Also, this error might show up because:",
78//                    "1. inside when() you don't call method on mock but on some other object.",
79//                    "2. inside when() you don't call static method, but class has not been prepared.",
80//                    ""
81//            ));
82//        }
83//
84//    }
85}
86
Full Screen
copy
1/*
2 * Copyright (c) 2007 Mockito contributors
3 * This program is made available under the terms of the MIT License.
4 */
5package org.mockito.internal;
6
7import org.mockito.*;
8import org.mockito.exceptions.misusing.NotAMockException;
9import org.mockito.internal.creation.MockSettingsImpl;
10import org.mockito.internal.invocation.finder.VerifiableInvocationsFinder;
11import org.mockito.internal.listeners.VerificationStartedNotifier;
12import org.mockito.internal.progress.MockingProgress;
13import org.mockito.internal.stubbing.DefaultLenientStubber;
14import org.mockito.internal.stubbing.InvocationContainerImpl;
15import org.mockito.internal.stubbing.OngoingStubbingImpl;
16import org.mockito.internal.stubbing.StubberImpl;
17import org.mockito.internal.util.DefaultMockingDetails;
18import org.mockito.internal.verification.MockAwareVerificationMode;
19import org.mockito.internal.verification.VerificationDataImpl;
20import org.mockito.internal.verification.VerificationModeFactory;
21import org.mockito.internal.verification.api.InOrderContext;
22import org.mockito.internal.verification.api.VerificationDataInOrder;
23import org.mockito.internal.verification.api.VerificationDataInOrderImpl;
24import org.mockito.invocation.Invocation;
25import org.mockito.invocation.MockHandler;
26import org.mockito.mock.MockCreationSettings;
27import org.mockito.plugins.MockMaker;
28import org.mockito.quality.Strictness;
29import org.mockito.stubbing.LenientStubber;
30import org.mockito.stubbing.OngoingStubbing;
31import org.mockito.stubbing.Stubber;
32import org.mockito.verification.VerificationMode;
33
34import java.util.Arrays;
35import java.util.List;
36import java.util.function.Function;
37
38import static org.mockito.internal.exceptions.Reporter.*;
39import static org.mockito.internal.progress.ThreadSafeMockingProgress.mockingProgress;
40import static org.mockito.internal.util.MockUtil.*;
41import static org.mockito.internal.verification.VerificationModeFactory.noInteractions;
42import static org.mockito.internal.verification.VerificationModeFactory.noMoreInteractions;
43
44@SuppressWarnings("unchecked")
45public class MockitoCore {
46
47    public boolean isTypeMockable(Class<?> typeToMock) {
48        return typeMockabilityOf(typeToMock).mockable();
49    }
50
51    public <T> T mock(Class<T> typeToMock, MockSettings settings) {
52        if (!MockSettingsImpl.class.isInstance(settings)) {
53            throw new IllegalArgumentException(
54                    "Unexpected implementation of '"
55                            + settings.getClass().getCanonicalName()
56                            + "'\n"
57                            + "At the moment, you cannot provide your own implementations of that class.");
58        }
59        MockSettingsImpl impl = MockSettingsImpl.class.cast(settings);
60        MockCreationSettings<T> creationSettings = impl.build(typeToMock);
61        T mock = createMock(creationSettings);
62        mockingProgress().mockingStarted(mock, creationSettings);
63        return mock;
64    }
65
66    public <T> MockedStatic<T> mockStatic(Class<T> classToMock, MockSettings settings) {
67        if (!MockSettingsImpl.class.isInstance(settings)) {
68            throw new IllegalArgumentException(
69                    "Unexpected implementation of '"
70                            + settings.getClass().getCanonicalName()
71                            + "'\n"
72                            + "At the moment, you cannot provide your own implementations of that class.");
73        }
74        MockSettingsImpl impl = MockSettingsImpl.class.cast(settings);
75        MockCreationSettings<T> creationSettings = impl.buildStatic(classToMock);
76        MockMaker.StaticMockControl<T> control = createStaticMock(classToMock, creationSettings);
77        control.enable();
78        mockingProgress().mockingStarted(classToMock, creationSettings);
79        return new MockedStaticImpl<>(control);
80    }
81
82    public <T> MockedConstruction<T> mockConstruction(
83            Class<T> typeToMock,
84            Function<MockedConstruction.Context, ? extends MockSettings> settingsFactory,
85            MockedConstruction.MockInitializer<T> mockInitializer) {
86        Function<MockedConstruction.Context, MockCreationSettings<T>> creationSettings =
87                context -> {
88                    MockSettings value = settingsFactory.apply(context);
89                    if (!MockSettingsImpl.class.isInstance(value)) {
90                        throw new IllegalArgumentException(
91                                "Unexpected implementation of '"
92                                        + value.getClass().getCanonicalName()
93                                        + "'\n"
94                                        + "At the moment, you cannot provide your own implementations of that class.");
95                    }
96                    MockSettingsImpl impl = MockSettingsImpl.class.cast(value);
97                    return impl.build(typeToMock);
98                };
99        MockMaker.ConstructionMockControl<T> control =
100                createConstructionMock(typeToMock, creationSettings, mockInitializer);
101        control.enable();
102        return new MockedConstructionImpl<>(control);
103    }
104
105    public <T> OngoingStubbing<T> when(T methodCall) {
106        MockingProgress mockingProgress = mockingProgress();
107        mockingProgress.stubbingStarted();
108        @SuppressWarnings("unchecked")
109        OngoingStubbing<T> stubbing = (OngoingStubbing<T>) mockingProgress.pullOngoingStubbing();
110        if (stubbing == null) {
111            mockingProgress.reset();
112            throw missingMethodInvocation();
113        }
114        return stubbing;
115    }
116
117    public <T> T verify(T mock, VerificationMode mode) {
118        if (mock == null) {
119            throw nullPassedToVerify();
120        }
121        MockingDetails mockingDetails = mockingDetails(mock);
122        if (!mockingDetails.isMock()) {
123            throw notAMockPassedToVerify(mock.getClass());
124        }
125        assertNotStubOnlyMock(mock);
126        MockHandler handler = mockingDetails.getMockHandler();
127        mock =
128                (T)
129                        VerificationStartedNotifier.notifyVerificationStarted(
130                                handler.getMockSettings().getVerificationStartedListeners(),
131                                mockingDetails);
132
133        MockingProgress mockingProgress = mockingProgress();
134        VerificationMode actualMode = mockingProgress.maybeVerifyLazily(mode);
135        mockingProgress.verificationStarted(
136                new MockAwareVerificationMode(
137                        mock, actualMode, mockingProgress.verificationListeners()));
138        return mock;
139    }
140
141    public <T> void reset(T... mocks) {
142        MockingProgress mockingProgress = mockingProgress();
143        mockingProgress.validateState();
144        mockingProgress.reset();
145        mockingProgress.resetOngoingStubbing();
146
147        for (T m : mocks) {
148            resetMock(m);
149        }
150    }
151
152    public <T> void clearInvocations(T... mocks) {
153        MockingProgress mockingProgress = mockingProgress();
154        mockingProgress.validateState();
155        mockingProgress.reset();
156        mockingProgress.resetOngoingStubbing();
157
158        for (T m : mocks) {
159            getInvocationContainer(m).clearInvocations();
160        }
161    }
162
163    public void verifyNoMoreInteractions(Object... mocks) {
164        assertMocksNotEmpty(mocks);
165        mockingProgress().validateState();
166        for (Object mock : mocks) {
167            try {
168                if (mock == null) {
169                    throw nullPassedToVerifyNoMoreInteractions();
170                }
171                InvocationContainerImpl invocations = getInvocationContainer(mock);
172                assertNotStubOnlyMock(mock);
173                VerificationDataImpl data = new VerificationDataImpl(invocations, null);
174                noMoreInteractions().verify(data);
175            } catch (NotAMockException e) {
176                throw notAMockPassedToVerifyNoMoreInteractions();
177            }
178        }
179    }
180
181    public void verifyNoInteractions(Object... mocks) {
182        assertMocksNotEmpty(mocks);
183        mockingProgress().validateState();
184        for (Object mock : mocks) {
185            try {
186                if (mock == null) {
187                    throw nullPassedToVerifyNoMoreInteractions();
188                }
189                InvocationContainerImpl invocations = getInvocationContainer(mock);
190                assertNotStubOnlyMock(mock);
191                VerificationDataImpl data = new VerificationDataImpl(invocations, null);
192                noInteractions().verify(data);
193            } catch (NotAMockException e) {
194                throw notAMockPassedToVerifyNoMoreInteractions();
195            }
196        }
197    }
198
199    public void verifyNoMoreInteractionsInOrder(List<Object> mocks, InOrderContext inOrderContext) {
200        mockingProgress().validateState();
201        VerificationDataInOrder data =
202                new VerificationDataInOrderImpl(
203                        inOrderContext, VerifiableInvocationsFinder.find(mocks), null);
204        VerificationModeFactory.noMoreInteractions().verifyInOrder(data);
205    }
206
207    private void assertMocksNotEmpty(Object[] mocks) {
208        if (mocks == null || mocks.length == 0) {
209            throw mocksHaveToBePassedToVerifyNoMoreInteractions();
210        }
211    }
212
213    private void assertNotStubOnlyMock(Object mock) {
214        if (getMockHandler(mock).getMockSettings().isStubOnly()) {
215            throw stubPassedToVerify(mock);
216        }
217    }
218
219    public InOrder inOrder(Object... mocks) {
220        if (mocks == null || mocks.length == 0) {
221            throw mocksHaveToBePassedWhenCreatingInOrder();
222        }
223        for (Object mock : mocks) {
224            if (mock == null) {
225                throw nullPassedWhenCreatingInOrder();
226            }
227            if (!isMock(mock)) {
228                throw notAMockPassedWhenCreatingInOrder();
229            }
230            assertNotStubOnlyMock(mock);
231        }
232        return new InOrderImpl(Arrays.asList(mocks));
233    }
234
235    public Stubber stubber() {
236        return stubber(null);
237    }
238
239    public Stubber stubber(Strictness strictness) {
240        MockingProgress mockingProgress = mockingProgress();
241        mockingProgress.stubbingStarted();
242        mockingProgress.resetOngoingStubbing();
243        return new StubberImpl(strictness);
244    }
245
246    public void validateMockitoUsage() {
247        mockingProgress().validateState();
248    }
249
250    /**
251     * For testing purposes only. Is not the part of main API.
252     *
253     * @return last invocation
254     */
255    public Invocation getLastInvocation() {
256        OngoingStubbingImpl ongoingStubbing =
257                ((OngoingStubbingImpl) mockingProgress().pullOngoingStubbing());
258        List<Invocation> allInvocations = ongoingStubbing.getRegisteredInvocations();
259        return allInvocations.get(allInvocations.size() - 1);
260    }
261
262    public Object[] ignoreStubs(Object... mocks) {
263        for (Object m : mocks) {
264            InvocationContainerImpl container = getInvocationContainer(m);
265            List<Invocation> ins = container.getInvocations();
266            for (Invocation in : ins) {
267                if (in.stubInfo() != null) {
268                    in.ignoreForVerification();
269                }
270            }
271        }
272        return mocks;
273    }
274
275    public MockingDetails mockingDetails(Object toInspect) {
276        return new DefaultMockingDetails(toInspect);
277    }
278
279    public LenientStubber lenient() {
280        return new DefaultLenientStubber();
281    }
282}
283
Full Screen

Accelerate Your Automation Test Cycles With LambdaTest

Leverage LambdaTest’s cloud-based platform to execute your automation tests in parallel and trim down your test execution time significantly. Your first 100 automation testing minutes are on us.

Try LambdaTest

Trigger code on LambdaTest Cloud Grid

Execute automation tests with on a cloud-based Grid of 3000+ real browsers and operating systems for both web and mobile applications.

Test now for Free
LambdaTestX

We use cookies to give you the best experience. Cookies help to provide a more personalized experience and relevant advertising for you, and web analytics for us. Learn More in our Cookies policy, Privacy & Terms of service

Allow Cookie
Sarah

I hope you find the best code examples for your project.

If you want to accelerate automated browser testing, try LambdaTest. Your first 100 automation testing minutes are FREE.

Sarah Elson (Product & Growth Lead)