Reputation: 936
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?
Upvotes: 2
Views: 2739
Reputation: 1499790
Your methodToTest
calls a.getSomeField()
, but the setup part of your test doesn't expect that call. You want something like:
Foo foo = new Foo();
EasyMock.expect(mock.getSomeField()).andReturn(foo);
Or to stub the call:
Foo foo = new Foo();
EasyMock.expect(mock.getSomeField()).andStubReturn(foo);
(before your call to mock.getSomething()
).
See this question for the differences between andReturn
and andStubReturn
.
Upvotes: 2