I am trying to write a test for legacy code that is looking like this:
public class TestedClass {
private A a = StaticFactory.createA();
private B b = StaticFactory.createB();
// No default constructor
// code using A and B classes
}
As far as my understanding of Mockito goes, I know that I can not mock static methods, however I know that I can use a little trick and externalize creation of this object to package-private methods like this:
public class TestedClass {
private A a;
private B b;
TestedClass() {
a = createA();
b = createB();
}
A createA() {
return StaticFactory.createA();
}
B createB() {
return StaticFactory.createB();
}
// code using A and B classes
}
But using this construction I am unable to create spy of TestedClass
, it has to be already a spy to use doReturn(..)
constructions so test like this won`t work:
public class TestedClassTest {
TestedClass testedClass;
A mockA;
B mockB;
@Before
public void setUp() {
mockA = mock(A.class);
mockB = mock(B.class);
testedClass = Mockito.spy(new TestedClass());
doReturn(mockA).when(testedClass).createA();
doReturn(mockB).when(testedClass).createB();
}
}
Is there any other way to change behaviour of createA
and createB
methods that are getting fired in constructor to ensure that I have mocks instances?
In this case, StaticFactory.createA()
is run and it is throwing exception (just under tests), unabling me to finish initialization of tests.
Running pl.tbawor.TestedClassTest
Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.168 sec <<< FAILURE!
shouldTestSomething(pl.tbawor.TestedClassTest) Time elapsed: 0.114 sec <<< ERROR!
java.lang.NullPointerException
at pl.tbawor.StaticFactory.createA(TestedClass.java:32)
at pl.tbawor.TestedClass.createA(TestedClass.java:14)
at pl.tbawor.TestedClass.<init>(TestedClass.java:9)
at pl.tbawor.TestedClassTest.setUp(TestedClassTest.java:26)
My goal is to avoid running original methods for creation A
and B
objects to prevent exception from being thrown.
Also as this is legacy project, I am unable to add any additional libraries (PowerMock).
I`ll add that TestingClass modification should be as little as possible.