Lets say I have the following code:
Mocked object class
public class SomeClass {
private Foo someField;
public SomeClass {
someField = new Foo();
}
public Foo getSomeField { return someField; }
public void getSomething() {}
public boolean doSomething(Object object) {}
}
Next I have test suite
public class TestSuite {
private ClassToTest classToTest;
private SomeClass mock;
@Before
public void setUp() {
classToTest = new ClassToTest();
mock = EasyMock.createMock(SomeClass.class);
}
@Test
public void testMethod() throws Exception {
mock.getSomething();
EasyMock.replay(mock);
classToTest.methodToTest(mock); //Where methodToTest accepts SomeClass and int
EasyMock.verify(mock);
}
}
And method which is being tested
public void methodToTest(SomeClass a) {
//Logic here
Foo b = a.getSomeField();
b.do(); // <--- null pointer exception here because someField isn't initialized
a.getSomething(); // <--- thing I want to test if it is being called, but can't due to exception prior to this line
//Logic after
}
I am stuck.. So yea basically SomeClass isn’t initialized like I wanted to. Is there any workaround? Or maybe any other frameworks which can do something like that?
Your
methodToTestcallsa.getSomeField(), but the setup part of your test doesn’t expect that call. You want something like:Or to stub the call:
(before your call to
mock.getSomething()).See this question for the differences between
andReturnandandStubReturn.