I need to write a JUnit test for the following (simplified) method:
public String getPreviousName(TreeEntry entry) { if (entry.getPrevious() != null) { return entry.getPrevious().getName(); } else { return entry.getName(); } }
I just don't know how I should check this out. I could either
a) Use Mocks to grind the parameter and its previous record or
b) Create a real TreeEntry and a real previous record
The problem with using mocks is that I have to say in the test case which method the actual implementation should use, for example. here I say that the correct name is obtained through getPrevious () TreeEntry, and then through getName () of this previous record (without considering the case if null, because this is basically not a problem):
TreeEntry mockEntry = mock(TreeEntry.class); TreeEntry mockPreviousEntry = mock(TreeEntry.class); when(mockEntry.getPrevious()).thenReturn(mockPreviousEntry); when(mockPreviousEntry.getName()).thenReturn("testName"); assertEquals("testName", classUnderTest.getPreviousName(mockEntry));
But a developer can, for example, implement it like this:
return NameService.getName(entry.getPrevious());
It just doesn't matter for the test.
However, if I use classic unit testing without layouts, I have another problem. The TreeEntry constructor is very complex. It has 5 parameters that need valid objects. Therefore, it is very difficult to create something like:
TreeEntry entry = new TreeEntry(...); TreeEntry previousEntry = new TreeEntry(...); entry.setPrevious(previousEntry); previousEntry.setName("testName"); assertEquals("testName", classUnderTest.getPreviousName(entry));
The code will be much longer than this, because the constructors take complex parameters. Another thing is that the designer refers to the file system to load its contents from there, so it adds to the slowdown of the modules.
Using the classic approach, it also ties the test a lot more to the TreeEntry implementation. Because if something has changed in TreeEntry with the constructors or setting up the previous record, it will also need to be changed in the test. And if he forgets, this will cause the test to fail even hard, the class test is not TreeEntry.
What would you say is the correct way to unit test this?
I personally tend to be ridiculed more. Maybe we can say that in the test case I already indicate which are the co-authors of the tested class, because this in some way also relates more to design than to implementation?
Regards, Alex