Say you have the following class that you would like to test:
public class SomeService { public String someMethod(SomeEntity someEntity) { return someEntity.getSomeProperty(); } }
SomeEntity is as follows:
public class SomeEntity { private String someProperty; public getSomeProperty() { return this.someProperty; } }
The statement you would like to make may be as follows:
String result = someService.someMethod(someEntity); assertThat(result).isEqualTo("someValue");
How can you do this test work?
1) Add setter for 'someProperty' to the SomeEntity class. I do not think this is a good solution because you do not change the production code so that your tests work.
2) Use ReflectionUtils to set the value of this field. The test will look like this:
public class TestClass { private SomeService someService; @Test public void testSomeProperty() { SomeEntity someEntity = new SomeEntity(); ReflectionTestUtils.setField(someEntity, "someProperty", "someValue"); String result = someService.someMethod(someEntity); assertThat(result).isEqualTo("someValue"); } }
3) You create an inner class in your test class that extends the SomeEntity class and adds an installer for this field. However, for this you will also need to change the SomeEntity class, because the field must be “protected” instead of 'private'. A testing class might look like this:
public class TestClass { private SomeService someService; @Test public void testSomeProperty() { SomeEntityWithSetters someEntity = new SomeEntityTestWithSetters(); someEntity.setSomeProperty("someValue"); String result = someService.someMethod(someEntity); assertThat(result).isEqualTo("someValue"); } public class SomeEntityWithSetters extends SomeEntity { public setSomeProperty(String someProperty) { this.someProperty = someProperty; } } }
4) You use Mockito to mock SomeEntity. It seems great if you only need to make fun of only one property in the class, but what if you need to mock 10 properties. The test may look like this:
public class TestClass { private SomeService someService; @Test public void testSomeProperty() { SomeEntity someEntity = mock(SomeEntity.class); when(someEntity.getSomeProperty()).thenReturn("someValue"); String result = someService.someMethod(someEntity); assertThat(result).isEqualTo("someValue"); } }