Best Powermock code snippet using org.powermock.reflect.context.OneInstanceAndOneStaticFieldOfSameTypeContext
Source:WhiteBoxTest.java  
...22import org.powermock.reflect.context.InstanceFieldsNotInTargetContext;23import org.powermock.reflect.context.MyContext;24import org.powermock.reflect.context.MyIntContext;25import org.powermock.reflect.context.MyStringContext;26import org.powermock.reflect.context.OneInstanceAndOneStaticFieldOfSameTypeContext;27import org.powermock.reflect.exceptions.FieldNotFoundException;28import org.powermock.reflect.exceptions.MethodNotFoundException;29import org.powermock.reflect.exceptions.TooManyFieldsFoundException;30import org.powermock.reflect.exceptions.TooManyMethodsFoundException;31import org.powermock.reflect.internal.WhiteboxImpl;32import org.powermock.reflect.matching.FieldMatchingStrategy;33import org.powermock.reflect.testclasses.AbstractClass;34import org.powermock.reflect.testclasses.AnInterface;35import org.powermock.reflect.testclasses.Child;36import org.powermock.reflect.testclasses.ClassWithAMethod;37import org.powermock.reflect.testclasses.ClassWithChildThatHasInternalState;38import org.powermock.reflect.testclasses.ClassWithInterfaceConstructors;39import org.powermock.reflect.testclasses.ClassWithInterfaceConstructors.ConstructorInterface;40import org.powermock.reflect.testclasses.ClassWithInterfaceConstructors.ConstructorInterfaceImpl;41import org.powermock.reflect.testclasses.ClassWithInternalState;42import org.powermock.reflect.testclasses.ClassWithList;43import org.powermock.reflect.testclasses.ClassWithObjectConstructors;44import org.powermock.reflect.testclasses.ClassWithOverloadedConstructors;45import org.powermock.reflect.testclasses.ClassWithOverloadedMethods;46import org.powermock.reflect.testclasses.ClassWithOverriddenMethod;47import org.powermock.reflect.testclasses.ClassWithPrimitiveConstructors;48import org.powermock.reflect.testclasses.ClassWithPrivateMethods;49import org.powermock.reflect.testclasses.ClassWithSerializableState;50import org.powermock.reflect.testclasses.ClassWithSeveralMethodsWithSameName;51import org.powermock.reflect.testclasses.ClassWithSeveralMethodsWithSameNameOneWithoutParameters;52import org.powermock.reflect.testclasses.ClassWithSimpleInternalState;53import org.powermock.reflect.testclasses.ClassWithStaticAndInstanceInternalStateOfSameType;54import org.powermock.reflect.testclasses.ClassWithStaticMethod;55import org.powermock.reflect.testclasses.ClassWithUniquePrivateMethods;56import org.powermock.reflect.testclasses.ClassWithVarArgsConstructor;57import org.powermock.reflect.testclasses.ClassWithVarArgsConstructor2;58import java.io.InputStream;59import java.io.Serializable;60import java.lang.reflect.Field;61import java.lang.reflect.Method;62import java.lang.reflect.Proxy;63import java.sql.Connection;64import java.util.Set;65import static org.assertj.core.api.Assertions.assertThat;66import static org.junit.Assert.assertArrayEquals;67import static org.junit.Assert.assertEquals;68import static org.junit.Assert.assertNotNull;69import static org.junit.Assert.assertNull;70import static org.junit.Assert.assertSame;71import static org.junit.Assert.assertTrue;72import static org.junit.Assert.fail;73/**74 * Tests the WhiteBox's functionality.75 */76public class WhiteBoxTest {77	@Rule78	public ExpectedException expectedException = ExpectedException.none();79	@Test80	public void testFindMethod_classContainingMethodWithNoParameters() throws Exception {81		Method expected = ClassWithSeveralMethodsWithSameNameOneWithoutParameters.class.getMethod("getDouble");82		Method actual = WhiteboxImpl.findMethodOrThrowException(83				ClassWithSeveralMethodsWithSameNameOneWithoutParameters.class, "getDouble");84		assertEquals(expected, actual);85	}86    @Test87    public void testFindMethod_classContainingOnlyMethodsWithParameters() throws Exception {88        try {89            WhiteboxImpl.findMethodOrThrowException(ClassWithSeveralMethodsWithSameName.class, "getDouble");90            fail("Should throw runtime exception!");91        } catch (RuntimeException e) {92            assertTrue("Error message did not match", e.getMessage().contains(93                    "Several matching methods found, please specify the argument parameter types"));94        }95    }96    @Test97    public void testFindMethod_noMethodFound() throws Exception {98        try {99            WhiteboxImpl.findMethodOrThrowException(ClassWithSeveralMethodsWithSameName.class, "getDouble2");100            fail("Should throw runtime exception!");101        } catch (RuntimeException e) {102            assertEquals("Error message did not match",103                         "No method found with name 'getDouble2' with parameter types: [ <none> ] in class "104                                 + ClassWithSeveralMethodsWithSameName.class.getName() + ".", e.getMessage());105        }106    }107    @Test108    public void testGetInternalState_object() throws Exception {109        ClassWithInternalState tested = new ClassWithInternalState();110        tested.increaseInteralState();111        Object internalState = Whitebox.getInternalState(tested, "internalState");112        assertTrue("InternalState should be instanceof Integer", internalState instanceof Integer);113        assertEquals(1, internalState);114    }115    @SuppressWarnings("deprecation")116    @Test117    public void testGetInternalState_parmaterizedType() throws Exception {118        ClassWithInternalState tested = new ClassWithInternalState();119        tested.increaseInteralState();120        int internalState = Whitebox.getInternalState(tested, "internalState", tested.getClass(), int.class);121        assertEquals(1, internalState);122    }123    @Test124    public void testSetInternalState() throws Exception {125        ClassWithInternalState tested = new ClassWithInternalState();126        tested.increaseInteralState();127        Whitebox.setInternalState(tested, "anotherInternalState", 2);128        assertEquals(2, tested.getAnotherInternalState());129    }130    @Test131    public void testSetInternalStateWithMultipleValues() throws Exception {132        ClassWithInternalState tested = new ClassWithInternalState();133        final ClassWithPrivateMethods classWithPrivateMethods = new ClassWithPrivateMethods();134        final String stringState = "someStringState";135        Whitebox.setInternalState(tested, classWithPrivateMethods, stringState);136        assertEquals(stringState, Whitebox.getInternalState(tested, String.class));137        assertSame(classWithPrivateMethods, Whitebox.getInternalState(tested, ClassWithPrivateMethods.class));138    }139    @Test140    public void testSetInternalState_superClass() throws Exception {141        ClassWithChildThatHasInternalState tested = new ClassWithChildThatHasInternalState();142        tested.increaseInteralState();143        Whitebox.setInternalState(tested, "anotherInternalState", 2, ClassWithInternalState.class);144        assertEquals(2, tested.getAnotherInternalState());145    }146    @Test147    public void testGetInternalState_superClass_object() throws Exception {148        ClassWithChildThatHasInternalState tested = new ClassWithChildThatHasInternalState();149        Object internalState = Whitebox.getInternalState(tested, "internalState", ClassWithInternalState.class);150        assertEquals(0, internalState);151    }152    @SuppressWarnings("deprecation")153    @Test154    public void testGetInternalState_superClass_parameterized() throws Exception {155        ClassWithChildThatHasInternalState tested = new ClassWithChildThatHasInternalState();156        int internalState = Whitebox.getInternalState(tested, "internalState", ClassWithInternalState.class, int.class);157        assertEquals(0, internalState);158    }159    @Test160    public void testInvokePrivateMethod_primtiveType() throws Exception {161        assertTrue(Whitebox.<Boolean>invokeMethod(new ClassWithPrivateMethods(), "primitiveMethod", 8.2));162    }163    @Test164    public void testInvokePrivateMethod_primtiveType_withoutSpecifyingMethodName() throws Exception {165        assertTrue((Boolean) Whitebox.invokeMethod(new ClassWithUniquePrivateMethods(), 8.2d, 8.4d));166    }167    /**168     * This test actually invokes the <code>finalize</code> method of169     * <code>java.lang.Object</code> because we supply no method name and no170     * arguments. <code>finalize</code> is thus the first method found and it'll171     * be executed.172     *173     * @throws Exception174     */175    @Test176    @Ignore("Invokes different methods on PC and MAC (hashCode on mac)")177    public void testInvokePrivateMethod_withoutSpecifyingMethodName_noArguments() throws Exception {178        assertNull(Whitebox.invokeMethod(new ClassWithUniquePrivateMethods()));179    }180    @Test181    public void testInvokePrivateMethod_withoutSpecifyingMethodName_assertThatNullWorks() throws Exception {182        assertTrue(Whitebox.invokeMethod(new ClassWithUniquePrivateMethods(), 8.2d, 8.3d, null) instanceof Object);183    }184    /**185     * This test should actually fail since equals takes an Object and we pass186     * in a primitive wrapped as a Double. Thus PowerMock cannot determine187     * whether to invoke the single argument method defined in188     * {@link ClassWithUniquePrivateMethods} or the189     * {@link Object#equals(Object)} method because we could potentially invoke190     * equals with a Double.191     */192    @Test(expected = TooManyMethodsFoundException.class)193    public void testInvokePrivateMethod_withoutSpecifyingMethodName_onlyOneArgument() throws Exception {194        Whitebox.invokeMethod(new ClassWithUniquePrivateMethods(), 8.2d);195    }196    @Test(expected = TooManyMethodsFoundException.class)197    public void testInvokeStaticPrivateMethod_withoutSpecifyingMethodName_onlyOneArgument() throws Exception {198        assertTrue((Boolean) Whitebox.invokeMethod(ClassWithUniquePrivateMethods.class, 8.2d));199    }200    @Test201    public void testInvokePrivateMethod_primtiveType_Wrapped() throws Exception {202        assertTrue((Boolean) Whitebox.invokeMethod(new ClassWithPrivateMethods(), "primitiveMethod", new Double(8.2)));203    }204    @Test205    public void testInvokePrivateMethod_wrappedType() throws Exception {206        assertTrue((Boolean) Whitebox.invokeMethod(new ClassWithPrivateMethods(), "wrappedMethod", new Double(8.2)));207    }208    @Test209    public void testInvokePrivateMethod_wrappedType_primitive() throws Exception {210        assertTrue((Boolean) Whitebox.invokeMethod(new ClassWithPrivateMethods(), "wrappedMethod", 8.2));211    }212    @Test213    public void testMethodWithPrimitiveIntAndString_primitive() throws Exception {214        assertEquals("My int value is: " + 8, Whitebox.invokeMethod(new ClassWithPrivateMethods(),215                                                                    "methodWithPrimitiveIntAndString", 8, "My int value is: "));216    }217    @Test218    public void testMethodWithPrimitiveIntAndString_Wrapped() throws Exception {219        assertEquals("My int value is: " + 8, Whitebox.invokeMethod(new ClassWithPrivateMethods(),220                                                                    "methodWithPrimitiveIntAndString", Integer.valueOf(8), "My int value is: "));221    }222    @Test223    public void testMethodWithPrimitiveAndWrappedInt_primtive_wrapped() throws Exception {224        assertEquals(17, Whitebox.invokeMethod(new ClassWithPrivateMethods(), "methodWithPrimitiveAndWrappedInt",225                                               new Class[]{int.class, Integer.class}, 9, Integer.valueOf(8)));226    }227    @Test228    public void testStaticState() {229        int expected = 123;230        Whitebox.setInternalState(ClassWithInternalState.class, "staticState", expected);231        assertEquals(expected, ClassWithInternalState.getStaticState());232        assertEquals(expected, Whitebox.getInternalState(ClassWithInternalState.class, "staticState"));233    }234	@Test235	public void testStaticFinalPrimitiveState() {236		expectedException.expect(IllegalArgumentException.class);237		expectedException.expectMessage("You are trying to set a private static final primitive. Try using an object like Integer instead of int!");238		Whitebox.setInternalState(ClassWithInternalState.class, "staticFinalIntState", 123);239	}240	@Test241	public void testStaticFinalStringState() throws NoSuchFieldException {242		expectedException.expect(IllegalArgumentException.class);243		expectedException.expectMessage("You are trying to set a private static final String. Cannot set such fields!");244		Whitebox.setInternalState(ClassWithInternalState.class, "staticFinalStringState", "Brand new string");245	}246	@Test247	public void testStaticFinalObject() throws NoSuchFieldException {248		int modifiersBeforeSet = ClassWithInternalState.class.getDeclaredField("staticFinalIntegerState").getModifiers();249		Integer newValue = ClassWithInternalState.getStaticFinalIntegerState() + 1;250		Whitebox.setInternalState(ClassWithInternalState.class, "staticFinalIntegerState", newValue);251		int modifiersAfterSet = ClassWithInternalState.class.getDeclaredField("staticFinalIntegerState").getModifiers();252		assertEquals(newValue, ClassWithInternalState.getStaticFinalIntegerState());253		assertEquals(modifiersBeforeSet, modifiersAfterSet);254	}255    /**256     * Verifies that the http://code.google.com/p/powermock/issues/detail?id=6257     * is fixed.258     */259    @Test(expected = IllegalArgumentException.class)260    public void testInvokeMethodWithNullParameter() throws Exception {261        Whitebox.invokeMethod(null, "method");262    }263    @Test(expected = IllegalArgumentException.class)264    public void testInvokeConstructorWithNullParameter() throws Exception {265        Whitebox.invokeConstructor(null, "constructor");266    }267    @Test(expected = IllegalArgumentException.class)268    public void testGetInternalWithNullParameter() throws Exception {269        Whitebox.getInternalState(null, "state");270    }271    @Test(expected = IllegalArgumentException.class)272    public void testSetInternalWithNullParameter() throws Exception {273        Whitebox.setInternalState(null, "state", new Object());274    }275    @Test276    public void testInstantiateVarArgsOnlyConstructor() throws Exception {277        final String argument1 = "argument1";278        final String argument2 = "argument2";279        ClassWithVarArgsConstructor instance = Whitebox.invokeConstructor(ClassWithVarArgsConstructor.class, argument1,280                                                                          argument2);281        String[] strings = instance.getStrings();282        assertEquals(2, strings.length);283        assertEquals(argument1, strings[0]);284        assertEquals(argument2, strings[1]);285    }286    @Test287    public void testInstantiateVarArgsOnlyConstructor_noArguments() throws Exception {288        ClassWithVarArgsConstructor instance = Whitebox.invokeConstructor(ClassWithVarArgsConstructor.class);289        String[] strings = instance.getStrings();290        assertEquals(0, strings.length);291    }292    @Test293    public void testInvokeVarArgsMethod_multipleValues() throws Exception {294        ClassWithPrivateMethods tested = new ClassWithPrivateMethods();295        assertEquals(6, Whitebox.invokeMethod(tested, "varArgsMethod", 1, 2, 3));296    }297    @Test298    public void testInvokeVarArgsMethod_noArguments() throws Exception {299        ClassWithPrivateMethods tested = new ClassWithPrivateMethods();300        assertEquals(0, Whitebox.invokeMethod(tested, "varArgsMethod"));301    }302    @Test303    public void testInvokeVarArgsMethod_oneArgument() throws Exception {304        ClassWithPrivateMethods tested = new ClassWithPrivateMethods();305        assertEquals(4, Whitebox.invokeMethod(tested, "varArgsMethod", 2));306    }307    @Test308    public void testInvokeVarArgsMethod_invokeVarArgsWithOneArgument() throws Exception {309        ClassWithPrivateMethods tested = new ClassWithPrivateMethods();310        assertEquals(1, Whitebox.invokeMethod(tested, "varArgsMethod", new Class<?>[]{int[].class}, 1));311    }312    @Test313    public void testInvokePrivateMethodWithASubTypeOfTheArgumentType() throws Exception {314        ClassWithPrivateMethods tested = new ClassWithPrivateMethods();315        ClassWithChildThatHasInternalState argument = new ClassWithChildThatHasInternalState();316        assertSame(argument, Whitebox.invokeMethod(tested, "methodWithObjectArgument", argument));317    }318    @Test319    public void testInvokePrivateMethodWithAClassArgument() throws Exception {320        ClassWithPrivateMethods tested = new ClassWithPrivateMethods();321        assertEquals(ClassWithChildThatHasInternalState.class, Whitebox.invokeMethod(tested, "methodWithClassArgument",322                                                                                     ClassWithChildThatHasInternalState.class));323    }324    @Test325    public void testSetInternalStateInChildClassWithoutSpecifyingTheChildClass() throws Exception {326        final int value = 22;327        final String fieldName = "internalState";328        ClassWithChildThatHasInternalState tested = new ClassWithChildThatHasInternalState() {329        };330        Whitebox.setInternalState(tested, fieldName, value);331        assertEquals(value, Whitebox.getInternalState(tested, fieldName));332    }333    @Test334    public void testSetInternalStateInClassAndMakeSureThatTheChildClassIsNotAffectedEvenThoughItHasAFieldWithTheSameName()335            throws Exception {336        final int value = 22;337        final String fieldName = "anotherInternalState";338        ClassWithChildThatHasInternalState tested = new ClassWithChildThatHasInternalState() {339        };340        Whitebox.setInternalState(tested, fieldName, value);341        assertEquals(value, Whitebox.getInternalState(tested, fieldName));342        assertEquals(-1, Whitebox.getInternalState(tested, fieldName, ClassWithInternalState.class));343    }344    @Test(expected = IllegalArgumentException.class)345    public void testSetInternalStateWithInvalidArgumentType() throws Exception {346        final int value = 22;347        final String fieldName = "internalState";348        ClassWithChildThatHasInternalState tested = new ClassWithChildThatHasInternalState() {349        };350        Whitebox.setInternalState(tested, fieldName, new Object());351        assertEquals(value, Whitebox.getInternalState(tested, fieldName));352    }353    @Test(expected = IllegalArgumentException.class)354    public void testSetInternalStateWithNull() throws Exception {355        final int value = 22;356        final String fieldName = "internalState";357        ClassWithChildThatHasInternalState tested = new ClassWithChildThatHasInternalState() {358        };359        Whitebox.setInternalState(tested, fieldName, (Object) null);360        assertEquals(value, Whitebox.getInternalState(tested, fieldName));361    }362    @Test363    public void testSetAndGetInternalStateBasedOnFieldType() throws Exception {364        final int value = 22;365        ClassWithChildThatHasInternalState tested = new ClassWithChildThatHasInternalState();366        Whitebox.setInternalState(tested, int.class, value);367        assertEquals(value, (int) Whitebox.getInternalState(tested, int.class));368        assertEquals(value, Whitebox.getInternalState(tested, "anotherInternalState"));369        assertEquals(value, Whitebox.getInternalState(tested, "anotherInternalState",370                                                      ClassWithChildThatHasInternalState.class));371    }372    @Test373    public void testSetAndGetInternalStateAtASpecificPlaceInTheHierarchyBasedOnFieldType() throws Exception {374        final int value = 22;375        ClassWithChildThatHasInternalState tested = new ClassWithChildThatHasInternalState();376        Whitebox.setInternalState(tested, int.class, value, ClassWithInternalState.class);377        assertEquals(42, (int) Whitebox.getInternalState(tested, int.class));378        assertEquals(value, (int) Whitebox.getInternalState(tested, int.class, ClassWithInternalState.class));379        assertEquals(value, Whitebox.getInternalState(tested, "staticState", ClassWithInternalState.class));380    }381    @Test382    public void testSetInternalStateBasedOnObjectType() throws Exception {383        final String value = "a string";384        ClassWithChildThatHasInternalState tested = new ClassWithChildThatHasInternalState();385        Whitebox.setInternalState(tested, value);386        assertEquals(value, Whitebox.getInternalState(tested, String.class));387    }388    @SuppressWarnings("deprecation")389    @Test390    public void testSetInternalStateBasedOnObjectTypeWhenArgumentIsAPrimitiveType() throws Exception {391        final int value = 22;392        ClassWithChildThatHasInternalState tested = new ClassWithChildThatHasInternalState();393        Whitebox.setInternalState(tested, value);394        assertEquals((Integer) value, Whitebox.getInternalState(tested, "anotherInternalState",395                                                                ClassWithChildThatHasInternalState.class, Integer.class));396    }397    @Test398    public void testSetInternalStateBasedOnObjectTypeWhenArgumentIsAPrimitiveTypeUsingGenerics() throws Exception {399        final int value = 22;400        ClassWithChildThatHasInternalState tested = new ClassWithChildThatHasInternalState();401        Whitebox.setInternalState(tested, value);402        assertEquals((Integer) value, Whitebox.<Integer>getInternalState(tested, "anotherInternalState",403                                                                         ClassWithChildThatHasInternalState.class));404    }405    @Test406    public void testSetInternalStateBasedOnObjectTypeAtASpecificPlaceInTheClassHierarchy() throws Exception {407        final String value = "a string";408        ClassWithChildThatHasInternalState tested = new ClassWithChildThatHasInternalState();409        Whitebox.setInternalState(tested, (Object) value, ClassWithInternalState.class);410        assertEquals(value, Whitebox.getInternalState(tested, "finalString"));411    }412    @Test413    public void testSetInternalStateBasedOnObjectTypeAtASpecificPlaceInTheClassHierarchyForPrimitiveType()414            throws Exception {415        final long value = 31;416        ClassWithChildThatHasInternalState tested = new ClassWithChildThatHasInternalState();417        Whitebox.setInternalState(tested, value, ClassWithInternalState.class);418        assertEquals(value, tested.getInternalLongState());419    }420    @Test421    public void testSetInternalStateBasedOnObjectTypeAtANonSpecificPlaceInTheClassHierarchyForPrimitiveType()422            throws Exception {423        final long value = 31;424        ClassWithChildThatHasInternalState tested = new ClassWithChildThatHasInternalState();425        Whitebox.setInternalState(tested, value);426        assertEquals(value, tested.getInternalLongState());427    }428    @Test429    public void testSetInternalMultipleOfSameTypeOnSpecificPlaceInHierarchy() throws Exception {430        final int value = 31;431        ClassWithChildThatHasInternalState tested = new ClassWithChildThatHasInternalState();432        try {433            Whitebox.setInternalState(tested, value, ClassWithInternalState.class);434            fail("should throw TooManyFieldsFoundException!");435        } catch (TooManyFieldsFoundException e) {436            assertEquals("Two or more fields matching type int.", e.getMessage());437        }438    }439    @Test440    public void testSetInternalMultipleOfSameType() throws Exception {441        final int value = 31;442        ClassWithInternalState tested = new ClassWithInternalState();443        try {444            Whitebox.setInternalState(tested, value);445            fail("should throw TooManyFieldsFoundException!");446        } catch (TooManyFieldsFoundException e) {447            assertEquals("Two or more fields matching type int.", e.getMessage());448        }449    }450    @Test451    public void testSetInternalStateBasedOnObjectSubClassTypeAtASpecificPlaceInTheClassHierarchy() throws Exception {452        final ClassWithPrivateMethods value = new ClassWithPrivateMethods() {453        };454        ClassWithChildThatHasInternalState tested = new ClassWithChildThatHasInternalState();455        Whitebox.setInternalState(tested, value, ClassWithInternalState.class);456        assertSame(value, tested.getClassWithPrivateMethods());457    }458    @Test459    public void testSetInternalStateBasedOnObjectSubClassType() throws Exception {460        final ClassWithPrivateMethods value = new ClassWithPrivateMethods() {461        };462        ClassWithChildThatHasInternalState tested = new ClassWithChildThatHasInternalState() {463        };464        Whitebox.setInternalState(tested, value);465        assertSame(value, tested.getClassWithPrivateMethods());466    }467    @Test468    public void testGetAllInstanceFields() throws Exception {469        Set<Field> allFields = Whitebox.getAllInstanceFields(new ClassWithChildThatHasInternalState());470        assertEquals(8, allFields.size());471    }472    @Test473    public void testGetAllStaticFields_assertNoFieldsFromParent() throws Exception {474        Set<Field> allFields = Whitebox.getAllStaticFields(ClassWithChildThatHasInternalState.class);475        assertEquals(0, allFields.size());476    }477	@Test478	public void testGetAllStaticFields() throws Exception {479		Set<Field> allFields = Whitebox.getAllStaticFields(ClassWithInternalState.class);480		assertEquals(4, allFields.size());481	}482    @Test483    public void testMethodWithNoMethodName_noMethodFound() throws Exception {484        try {485            Whitebox.getMethod(ClassWithInternalState.class, int.class);486            fail("Should throw MethodNotFoundException");487        } catch (MethodNotFoundException e) {488            assertEquals(489                    "No method was found with parameter types: [ int ] in class org.powermock.reflect.testclasses.ClassWithInternalState.",490                    e.getMessage());491        }492    }493    @Test494    public void testMethodWithNoMethodName_tooManyMethodsFound() throws Exception {495        try {496            Whitebox.getMethod(ClassWithSeveralMethodsWithSameName.class);497            fail("Should throw TooManyMethodsFoundException");498        } catch (TooManyMethodsFoundException e) {499            assertTrue(e500                               .getMessage()501                               .contains(502                                       "Several matching methods found, please specify the method name so that PowerMock can determine which method you're referring to"));503        }504    }505    @Test506    public void testMethodWithNoMethodName_ok() throws Exception {507        final Method method = Whitebox.getMethod(ClassWithSeveralMethodsWithSameName.class, double.class);508        assertEquals(method, ClassWithSeveralMethodsWithSameName.class.getDeclaredMethod("getDouble", double.class));509    }510    @Test511    public void testGetTwoMethodsWhenNoneOfThemAreFound() throws Exception {512        try {513            Whitebox.getMethods(ClassWithSeveralMethodsWithSameName.class, "notFound1", "notFound2");514        } catch (MethodNotFoundException e) {515            assertEquals(516                    "No methods matching the name(s) notFound1 or notFound2 were found in the class hierarchy of class org.powermock.reflect.testclasses.ClassWithSeveralMethodsWithSameName.",517                    e.getMessage());518        }519    }520    @Test521    public void testGetThreeMethodsWhenNoneOfThemAreFound() throws Exception {522        try {523            Whitebox.getMethods(ClassWithSeveralMethodsWithSameName.class, "notFound1", "notFound2", "notFound3");524        } catch (MethodNotFoundException e) {525            assertEquals(526                    "No methods matching the name(s) notFound1, notFound2 or notFound3 were found in the class hierarchy of class org.powermock.reflect.testclasses.ClassWithSeveralMethodsWithSameName.",527                    e.getMessage());528        }529    }530    /**531     * Asserts that <a532     * href="http://code.google.com/p/powermock/issues/detail?id=118">issue533     * 118</a> is fixed. Thanks to cemcatik for finding this.534     */535    @Test536    public void testInvokeConstructorWithBothNormalAndVarArgsParameter() throws Exception {537        ClassWithVarArgsConstructor2 instance = Whitebox.invokeConstructor(ClassWithVarArgsConstructor2.class, "first",538                                                                           "second", "third");539        assertArrayEquals(new String[]{"first", "second", "third"}, instance.getStrings());540    }541    /**542     * Asserts that <a543     * href="http://code.google.com/p/powermock/issues/detail?id=118">issue544     * 118</a> is fixed. Thanks to cemcatik for finding this.545     */546    @Test547    public void testInvokeMethodWithBothNormalAndVarArgsParameter() throws Exception {548        ClassWithPrivateMethods tested = new ClassWithPrivateMethods();549        assertEquals(4, Whitebox.invokeMethod(tested, "varArgsMethod2", 1, 2, 3));550    }551    @Test552    public void testInvokePrivateMethodWithArrayArgument() throws Exception {553        ClassWithPrivateMethods tested = new ClassWithPrivateMethods();554        assertEquals("Hello World", Whitebox.invokeMethod(tested, "evilConcatOfStrings", new Object[]{new String[]{555                "Hello ", "World"}}));556    }557    @Test558    public void testSetInternalStateFromContext_allStatesInSameOneContext() throws Exception {559        ClassWithSimpleInternalState tested = new ClassWithSimpleInternalState();560        MyContext context = new MyContext();561        Whitebox.setInternalStateFromContext(tested, context);562        assertEquals(context.getMyStringState(), tested.getSomeStringState());563        assertEquals(context.getMyIntState(), tested.getSomeIntState());564    }565    @Test566    public void testSetInternalStateFromContext_statesInDifferentContext() throws Exception {567        ClassWithSimpleInternalState tested = new ClassWithSimpleInternalState();568        MyIntContext myIntContext = new MyIntContext();569        MyStringContext myStringContext = new MyStringContext();570        Whitebox.setInternalStateFromContext(tested, myIntContext, myStringContext);571        assertEquals(myStringContext.getMyStringState(), tested.getSomeStringState());572        assertEquals(myIntContext.getSimpleIntState(), tested.getSomeIntState());573    }574    @Test575    public void testSetInternalStateFromContext_contextIsAClass() throws Exception {576        ClassWithSimpleInternalState tested = new ClassWithSimpleInternalState();577        Whitebox.setInternalStateFromContext(tested, MyContext.class);578        assertEquals(Whitebox.getInternalState(MyContext.class, long.class), (Long) tested.getSomeStaticLongState());579    }580    @Test581    public void testSetInternalStateFromContext_contextIsAClassAndAnInstance() throws Exception {582        ClassWithSimpleInternalState tested = new ClassWithSimpleInternalState();583        MyContext myContext = new MyContext();584        Whitebox.setInternalStateFromContext(tested, MyContext.class, myContext);585        assertEquals(myContext.getMyStringState(), tested.getSomeStringState());586        assertEquals(myContext.getMyIntState(), tested.getSomeIntState());587        assertEquals((Long) myContext.getMyLongState(), (Long) tested.getSomeStaticLongState());588    }589    @Test590    public void testSetInternalStateFromContext_contextHasOneInstanceAndOneStaticFieldOfSameType_onlyInstanceContext()591            throws Exception {592        ClassWithStaticAndInstanceInternalStateOfSameType.reset();593        ClassWithStaticAndInstanceInternalStateOfSameType tested = new ClassWithStaticAndInstanceInternalStateOfSameType();594        OneInstanceAndOneStaticFieldOfSameTypeContext context = new OneInstanceAndOneStaticFieldOfSameTypeContext();595        Whitebox.setInternalStateFromContext(tested, context);596        assertEquals(context.getMyStringState(), tested.getStringState());597        assertEquals("Static String state", tested.getStaticStringState());598    }599    @Test600    public void testSetInternalStateFromContext_contextHasOneInstanceAndOneStaticFieldOfSameType_onlyStaticContext()601            throws Exception {602        ClassWithStaticAndInstanceInternalStateOfSameType.reset();603        ClassWithStaticAndInstanceInternalStateOfSameType tested = new ClassWithStaticAndInstanceInternalStateOfSameType();604        Whitebox.setInternalStateFromContext(tested, OneInstanceAndOneStaticFieldOfSameTypeContext.class);605        assertEquals(OneInstanceAndOneStaticFieldOfSameTypeContext.getMyStaticStringState(), tested606                                                                                                     .getStaticStringState());607        assertEquals("String state", tested.getStringState());608    }609    @Test610    public void setInternalStateFromInstanceContextCopiesMatchingContextFieldsToTargetObjectByDefault()611            throws Exception {612        ClassWithSimpleInternalState tested = new ClassWithSimpleInternalState();613        InstanceFieldsNotInTargetContext fieldsNotInTargetContext = new InstanceFieldsNotInTargetContext();614        assertThat(tested.getSomeStringState()).isNotEqualTo(fieldsNotInTargetContext.getString());615        Whitebox.setInternalStateFromContext(tested, fieldsNotInTargetContext);616        assertEquals(tested.getSomeStringState(), fieldsNotInTargetContext.getString());617    }618    @Test619    public void setInternalStateFromInstanceContextCopiesMatchingContextFieldsToTargetObjectWhenSpecifyingMatchingStrategy()...Source:OneInstanceAndOneStaticFieldOfSameTypeContext.java  
...13 * See the License for the specific language governing permissions and14 * limitations under the License.15 */16package org.powermock.reflect.context;17public class OneInstanceAndOneStaticFieldOfSameTypeContext {18    private String myStringState = "myString";19    private static String myStaticStringState = "21L";20    public String getMyStringState() {21        return myStringState;22    }23    public static String getMyStaticStringState() {24        return myStaticStringState;25    }26}...OneInstanceAndOneStaticFieldOfSameTypeContext
Using AI Code Generation
1package org.powermock.reflect.testclasses;2import java.util.ArrayList;3import java.util.List;4import org.powermock.reflect.context.OneInstanceAndOneStaticFieldOfSameTypeContext;5public class ClassWithStaticAndInstanceFieldsOfSameType {6    public static final List<String> staticField = new ArrayList<String>();7    public final List<String> instanceField = new ArrayList<String>();8    public static void main(String[] args) {9        OneInstanceAndOneStaticFieldOfSameTypeContext context = new OneInstanceAndOneStaticFieldOfSameTypeContext(10                ClassWithStaticAndInstanceFieldsOfSameType.class);11        context.addInstanceField("instanceField");12        context.addStaticField("staticField");13        context.enter();14        try {15            staticField.add("foo");16            ClassWithStaticAndInstanceFieldsOfSameType instance = new ClassWithStaticAndInstanceFieldsOfSameType();17            instance.instanceField.add("bar");18        } finally {19            context.exit();20        }21    }22}23package org.powermock.reflect.testclasses;24import java.util.ArrayList;25import java.util.List;26import org.powermock.reflect.context.OneInstanceAndOneStaticFieldOfSameTypeContext;27public class ClassWithStaticAndInstanceFieldsOfSameType {28    public static final List<String> staticField = new ArrayList<String>();29    public final List<String> instanceField = new ArrayList<String>();30    public static void main(String[] args) {31        OneInstanceAndOneStaticFieldOfSameTypeContext context = new OneInstanceAndOneStaticFieldOfSameTypeContext(32                ClassWithStaticAndInstanceFieldsOfSameType.class);33        context.addInstanceField("instanceField");34        context.addStaticField("staticField");35        context.enter();36        try {37            staticField.add("foo");38            ClassWithStaticAndInstanceFieldsOfSameType instance = new ClassWithStaticAndInstanceFieldsOfSameType();39            instance.instanceField.add("bar");40        } finally {41            context.exit();42        }43    }44}45package org.powermock.reflect.testclasses;46import java.util.ArrayList;47import java.util.List;48import org.powermock.reflect.context.OneInstanceAndOneStaticFieldOfSameTypeContext;OneInstanceAndOneStaticFieldOfSameTypeContext
Using AI Code Generation
1package org.powermock.reflect.testclasses;2import org.powermock.reflect.testclasses.ClassWithStaticField;3import org.powermock.reflect.testclasses.ClassWithStaticField;4public class ClassWithStaticField {5    private static ClassWithStaticField instance = new ClassWithStaticField();6    private static ClassWithStaticField instance2 = new ClassWithStaticField();7    public static ClassWithStaticField getInstance() {8        return instance;9    }10    public static ClassWithStaticField getInstance2() {11        return instance2;12    }13}14package org.powermock.reflect.testclasses;15public class ClassWithStaticField {16    private static ClassWithStaticField instance = new ClassWithStaticField();17    private static ClassWithStaticField instance2 = new ClassWithStaticField();18    public static ClassWithStaticField getInstance() {19        return instance;20    }21    public static ClassWithStaticField getInstance2() {22        return instance2;23    }24}25package org.powermock.reflect.testclasses;26public class ClassWithStaticField {27    private static ClassWithStaticField instance = new ClassWithStaticField();28    private static ClassWithStaticField instance2 = new ClassWithStaticField();29    public static ClassWithStaticField getInstance() {30        return instance;31    }32    public static ClassWithStaticField getInstance2() {33        return instance2;34    }35}36package org.powermock.reflect.testclasses;37public class ClassWithStaticField {38    private static ClassWithStaticField instance = new ClassWithStaticField();39    private static ClassWithStaticField instance2 = new ClassWithStaticField();40    public static ClassWithStaticField getInstance() {41        return instance;42    }43    public static ClassWithStaticField getInstance2() {44        return instance2;45    }46}47package org.powermock.reflect.testclasses;48import org.powermock.reflect.testclasses.ClassWithStaticField;49import org.powermock.reflect.testclasses.ClassWithStaticField;50public class ClassWithStaticField {51    private static ClassWithStaticField instance = new ClassWithStaticField();52    private static ClassWithStaticField instance2 = new ClassWithStaticField();53    public static ClassWithStaticField getInstance() {54        return instance;55    }56    public static ClassWithStaticField getInstance2() {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!!
