/** * Use reflection to set the given field * * @param klass * @param instance null if field is static * @param fieldName * @param value * @param <T> the class type * @throws IllegalArgumentException if klass or fieldName are null * @throws FalsePositiveException if the the field does not exist anymore (eg due to refactoring) */ public static <T> void setVariable(Class<T> klass, T instance, String fieldName, Object value) throws IllegalArgumentException, FalsePositiveException { setVariable(klass,instance,fieldName,value,null); }
@Constraints(noNullInputs = true, notMutable = true, noDirectInsertion = true) public static <T> void inject(@BoundInputVariable(initializer = true, atMostOnceWithSameParameters = true) T instance, Class<?> klass, String fieldName, Object value) throws IllegalArgumentException { try { PrivateAccess.setVariable(klass, instance, fieldName, value, InjectionList.getList()); } catch (FalsePositiveException e){ /* do not abort the test if failed to add dependency injection. This is quite different from private access: a PA does have effect on test, otherwise minimization would had removed them. But a dependency injection might have no impact whatsoever */ } }
@Test public void testSetField_serialVersionUID(){ try { //it should fail PrivateAccess.setVariable(FooFields.class, null, "serialVersionUID", 42l); Assert.fail(); } catch (IllegalArgumentException e){ //expected } }
@Test public void testSetField_static(){ PrivateAccess.setVariable(FooFields.class,null,"n",42); Assert.assertEquals(42, FooFields.getN()); }
@Test public void testSetField_error(){ PrivateAccess.setShouldNotFailTest(true); PrivateAccess.setVariable(FooFields.class, null, "a non-existing field", 42); Assert.fail(); // this should never be reached, as failed "Assumption" inside setVariable }
@Test public void testSetField_instance(){ FooFields foo = new FooFields(); PrivateAccess.setVariable(FooFields.class,foo,"s","bar"); Assert.assertEquals("bar",foo.getS()); }
@Test public void testSetField_fail_on_error(){ PrivateAccess.setShouldNotFailTest(false); try { PrivateAccess.setVariable(FooFields.class, null, "a non-existing field", 42); Assert.fail(); } catch (FalsePositiveException e){ Assert.fail(); } catch (RuntimeException e){ //Ok, expected } finally { PrivateAccess.setShouldNotFailTest(true); } }