FieldValueMutator { public void mutateTo(Object value) { boolean wasAccessible = field.isAccessible(); if (!wasAccessible) { field.setAccessible(true); } try { field.set(object, value); } catch (IllegalAccessException e) { throw new MockitoCollectionsException("Could not set field '" + field + "' on object '" + object + "' with value: '" + value + "' because field is not accessible", e); } catch (IllegalArgumentException e) { throw new MockitoCollectionsException("Could not set field '" + field + "' on object '" + object + "' with value '" + value + "' because value was of an incompatible type", e); } if (!wasAccessible) { try { field.setAccessible(false); } catch (Throwable t) { } } } FieldValueMutator(Object object, Field field); void mutateTo(Object value);  }
@Test public void shouldSetGivenPublicField() { Field field = getField("publicString"); FieldValueMutator mutator = new FieldValueMutator(support, field); Object value = "Some New Value"; mutator.mutateTo(value); assertEquals(value, support.publicString); assertFalse(field.isAccessible()); }
@Test public void shouldSetGivenPublicAccesibleField() { Field field = getField("publicString"); field.setAccessible(true); FieldValueMutator mutator = new FieldValueMutator(support, field); Object value = "Some New Value"; mutator.mutateTo(value); assertEquals(value, support.publicString); assertTrue(field.isAccessible()); }
@Test public void shouldSetGivenPrivateField() { Field field = getField("privateCollection"); FieldValueMutator mutator = new FieldValueMutator(support, field); Object value = mock(Collection.class); mutator.mutateTo(value); assertEquals(value, support.getPrivateCollection()); assertFalse(field.isAccessible()); }
@Test public void shouldFailToSetGivenIncompatibleType() { FieldValueMutator mutator = new FieldValueMutator(support, getField("privateCollection")); Object value = 100L; try { mutator.mutateTo(value); fail(); } catch (MockitoCollectionsException e) { assertTrue(e.getMessage().contains("incompatible type")); } }