A bad system design can lead to much hard work. In order to increase the unit tests coverage, I recently started to work on writing unit tests for some classes. One of the case is I want to test a method as follow:
1 2 3 4 5 6 7 8
publicfinal ReturnType getMethod(SomeRequest someRequest){ AnotherRequest anotherRequest = new AnotherRequest(someRequest); SomeResponse someResponse = SomeService.getInstance().someMethod(anotherRequest); SomeValue someValue = someResponse.getValue(); /** * Some processes with someValue.. */ }
The main purpose of this test is testing the process with someValue, so I should just mock the .getValue() method. But the thing is not that easy. Let me put more related classes here: SomeService.class
1 2 3 4 5 6 7 8 9 10 11 12 13
publicfinalclassSomeService{ privatestatic SomeService instance = new SomeService(); static { // A static block } protectedSomeService(){} publicstatic SomeService getInstance(){ return instance; } public SomeResponse someMethod(AnotherRequest anotherRequest){ // Implementation of the method.. } }
SomeResponse.class
1 2 3 4 5
publicclassSomeResponse{ public SomeValue getValue(){ // Implementation of getValue() } }
SomeValue.class
1 2 3 4 5 6 7 8 9
publicclassSomeValue{ private String name; privatevoidpopulateValue(PreDefinedType preDefinedType){ // Generate name from a preDefinedType, basically a black box. } public String getName(){ return name; } }