You've nearly got it. The problem is that the Class Under Test (CUT) is not built for unit testing - it has not really been TDD'd.
Think of it like this…
In the unit test
@Spy
on it@Mock
all of the other class/service/database (i.e. external dependencies) In order to avoid executing code that you are not strictly testing, you could abstract that code away into something that can be @Mock
ed.
In this very simple example, a function that creates an object will be difficult to test
public void doSomethingCool(String foo) {
MyObject obj = new MyObject(foo);
// can't do much with obj in a unit test unless it is returned
}
But a function that uses a service to get MyObject is easy to test, as we have abstracted the difficult/impossible to test code into something that makes this method testable.
public void doSomethingCool(String foo) {
MyObject obj = MyObjectService.getMeAnObject(foo);
}
as MyObjectService can be mocked and also verified that .getMeAnObject() is called with the foo variable.