Best Powermock code snippet using org.powermock.core.MockGateway.calledFromMockito
Source:MockGateway.java  
...28 */29public class MockGateway {30    /**31     * {@link #noMockito} is wrapped into it's own static class to make sure it is initialized not earlier than32     * {@link #calledFromMockito()} is called for the first time.33     */34    private static final class NoMockito {35        static final boolean noMockito = Package.getPackage("org.mockito") == null;36        private NoMockito() {}37    }38    public static final Object PROCEED = new Object();39    public static final Object SUPPRESS = new Object();40    /**41     * Used to tell the MockGateway that the next call should not be mocked42     * regardless if a {@link MethodInvocationControl} is found in the43     * {@link MockRepository}. Used to allow for e.g. recursive partial mocking.44     */45    public static final String DONT_MOCK_NEXT_CALL = "DontMockNextCall";46    /**47     * Tells PowerMock to mock standard methods. These are48     * {@link Object#toString()}, {@link Object#hashCode()} and49     * {@link Object#equals(Object)}. By default this is {@code true}.50     */51    public static boolean MOCK_STANDARD_METHODS = true;52    @SuppressWarnings("UnusedDeclaration")53    public static Object newInstanceCall(Class<?> type, Object[] args, Class<?>[] sig) throws Throwable {54        final NewInvocationControl<?> newInvocationControl = MockRepository.getNewInstanceControl(type);55        if (newInvocationControl != null) {56            /*57            * We need to deal with inner, local and anonymous inner classes58            * specifically. For example when new is invoked on an inner class59            * it seems like null is passed as an argument even though it60            * shouldn't. We correct this here.61            *62            * Seems with Javassist 3.17.1-GA & Java 7, the 'null' is passed as the last argument.63            */64            if (type.isMemberClass() && Modifier.isStatic(type.getModifiers())) {65                if (args.length > 066                        && ((args[0] == null && sig[0].getCanonicalName() == null)67                        || (args[args.length - 1] == null && sig[args.length - 1].getCanonicalName() == null))68                        && sig.length > 0) {69                    args = copyArgumentsForInnerOrLocalOrAnonymousClass(args, sig[0], false);70                }71            } else if (type.isLocalClass() || type.isAnonymousClass() || type.isMemberClass()) {72                if (args.length > 0 && sig.length > 0 && sig[0].equals(type.getEnclosingClass())) {73                    args = copyArgumentsForInnerOrLocalOrAnonymousClass(args, sig[0], true);74                }75            }76            return newInvocationControl.invoke(type, args, sig);77        }78        // Check if we should suppress the constructor code79        if (MockRepository.shouldSuppressConstructor(WhiteboxImpl.getConstructor(type, sig))) {80            return WhiteboxImpl.getFirstParentConstructor(type);81        }82        return PROCEED;83    }84    @SuppressWarnings("UnusedDeclaration")85    public static Object fieldCall(Object instanceOrClassContainingTheField, Class<?> classDefiningField,86                                   String fieldName, Class<?> fieldType) {87        if (MockRepository.shouldSuppressField(WhiteboxImpl.getField(classDefiningField, fieldName))) {88            return TypeUtils.getDefaultValue(fieldType);89        }90        return PROCEED;91    }92    public static Object staticConstructorCall(String className) {93        if (MockRepository.shouldSuppressStaticInitializerFor(className)) {94            return "suppress";95        }96        return PROCEED;97    }98    @SuppressWarnings("UnusedDeclaration")99    public static Object constructorCall(Class<?> type, Object[] args, Class<?>[] sig) throws Throwable {100        final Constructor<?> constructor = WhiteboxImpl.getConstructor(type, sig);101        if (MockRepository.shouldSuppressConstructor(constructor)) {102            return null;103        }104        return PROCEED;105    }106    /**107     * Tells PowerMock whether or not to mock108     * {@link java.lang.Object#getClass()}.109     */110    public static boolean MOCK_GET_CLASS_METHOD = false;111    /**112     * Tells PowerMock whether or not to mock113     * {@link java.lang.Class#isAnnotationPresent(Class)} and114     * {@link java.lang.Class#getAnnotation(Class)}.115     */116    public static boolean MOCK_ANNOTATION_METHODS = false;117    // used for instance methods118    @SuppressWarnings("UnusedDeclaration")119    public static Object methodCall(Object instance, String methodName, Object[] args, Class<?>[] sig,120                                    String returnTypeAsString) throws Throwable {121        return doMethodCall(instance, methodName, args, sig, returnTypeAsString);122    }123    // used for static methods124    @SuppressWarnings("UnusedDeclaration")125    public static Object methodCall(Class<?> type, String methodName, Object[] args, Class<?>[] sig,126                                    String returnTypeAsString) throws Throwable {127        return doMethodCall(type, methodName, args, sig, returnTypeAsString);128    }129    private static Object doMethodCall(Object object, String methodName, Object[] args, Class<?>[] sig,130                                       String returnTypeAsString) throws Throwable {131        if (!shouldMockMethod(methodName, sig)) {132            return PROCEED;133        }134        MockInvocation mockInvocation = new MockInvocation(object, methodName, sig);135        MethodInvocationControl methodInvocationControl = mockInvocation.getMethodInvocationControl();136        Object returnValue = null;137        // The following describes the equals non-static method.138        if (isEqualsMethod(mockInvocation) && !isStaticMethod(mockInvocation)) {139            returnValue = tryHandleEqualsMethod(mockInvocation);140        }141        if (returnValue != null) {142            return returnValue;143        }144        return doMethodCall(object, args, returnTypeAsString, mockInvocation, methodInvocationControl);145    }146    private static Object doMethodCall(Object object, Object[] args,147                                       String returnTypeAsString,148                                       MockInvocation mockInvocation,149                                       MethodInvocationControl methodInvocationControl) throws Throwable {150        Object returnValue;151        // At first should be checked that method not suppressed/stubbed, because otherwise for spies real152        // method is involved.153        // https://github.com/jayway/powermock/issues/327154        if (MockRepository.shouldSuppressMethod(mockInvocation.getMethod(), mockInvocation.getObjectType())) {155            returnValue = TypeUtils.getDefaultValue(returnTypeAsString);156        } else if (MockRepository.shouldStubMethod(mockInvocation.getMethod())) {157            returnValue = MockRepository.getMethodToStub(mockInvocation.getMethod());158        } else if (methodInvocationControl != null && methodInvocationControl.isMocked(mockInvocation.getMethod()) && shouldMockThisCall()) {159            returnValue = methodInvocationControl.invoke(object, mockInvocation.getMethod(), args);160            if (returnValue == SUPPRESS) {161                returnValue = TypeUtils.getDefaultValue(returnTypeAsString);162            }163        } else if (MockRepository.hasMethodProxy(mockInvocation.getMethod())) {164                /*165                 * We must temporary remove the method proxy when invoking the166                 * invocation handler because if the invocation handler delegates167                 * the call we will end up here again and we'll get a168                 * StackOverflowError.169                 */170            final InvocationHandler invocationHandler = MockRepository.removeMethodProxy(mockInvocation.getMethod());171            try {172                returnValue = invocationHandler.invoke(object, mockInvocation.getMethod(), args);173            } finally {174                // Set the method proxy again after the invocation175                MockRepository.putMethodProxy(mockInvocation.getMethod(), invocationHandler);176            }177        } else {178            returnValue = PROCEED;179        }180        return returnValue;181    }182    /*183     * Method handles exception cases with equals method.184     */185    private static Object tryHandleEqualsMethod(MockInvocation mockInvocation) {186        // Fix for Issue http://code.google.com/p/powermock/issues/detail?id=88187        // For some reason the method call to equals() on final methods is188        // intercepted and during the further processing in Mockito the same189        // equals() method is called on the same instance. A StackOverflowError190        // is the result. The following fix changes this by checking if the191        // method to be called is a final equals() method. In that case the192        // original method is called by returning PROCEED.193        if (mockInvocation.getMethod().getParameterTypes().length == 1194                    && mockInvocation.getMethod().getParameterTypes()[0] == Object.class195                    && Modifier.isFinal(mockInvocation.getMethod().getModifiers())) {196            return PROCEED;197        }198        if (calledFromMockito()){199            return PROCEED;200        }201        return null;202    }203    private static boolean isEqualsMethod(MockInvocation mockInvocation) {204        return "equals".equals(mockInvocation.getMethod().getName());205    }206    private static boolean isStaticMethod(MockInvocation mockInvocation) {207        return Modifier.isStatic(mockInvocation.getMethod().getModifiers());208    }209    private static boolean calledFromMockito() {210        if (NoMockito.noMockito) {211            return false;212        }213        StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();214        for (StackTraceElement stackTraceElement : stackTrace) {215            if (stackTraceElement.getClassName().startsWith("org.mockito.")){216                return true;217            }218        }219        return false;220    }221    private static boolean shouldMockMethod(String methodName, Class<?>[] sig) {222        if (isJavaStandardMethod(methodName, sig) && !MOCK_STANDARD_METHODS) {223            return false;...calledFromMockito
Using AI Code Generation
1    public void testMockedObject() {2        final MockGateway mockGateway = PowerMockito.mock(MockGateway.class);3        final Object obj = new Object();4        final Object obj1 = new Object();5        PowerMockito.when(mockGateway.callMockedObject(obj)).thenReturn(obj1);6        final Object result = calledFromMockito(mockGateway, obj);7        assertEquals(obj1, result);8    }9    private Object calledFromMockito(MockGateway mockGateway, Object obj) {10        return mockGateway.callMockedObject(obj);11    }12}13The following are the steps to use PowerMockito.mock() method:14Step 1: Create the object of the class that needs to be mocked using PowerMockito.mock() method. The object can be created using the following syntax:15PowerMockito.mock(classToMock);16PowerMockito.when(objectToMock.methodToMock()).thenReturn(valueToReturn);17objectToMock.methodToMock();18objectToMock.methodToMock();19objectToMock.methodToMock();20objectToMock.methodToMock();21objectToMock.methodToMock();22objectToMock.methodToMock();Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
