让我说我有以下代码:
模拟对象类
public class SomeClass {
private Foo someField;
public SomeClass {
someField = new Foo();
}
public Foo getSomeField { return someField; }
public void getSomething() {}
public boolean doSomething(Object object) {}
}
接下来我有测试套件
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);
}
}
正在测试的方法
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
}
我被困了..所以基本上SomeClass没有像我想的那样初始化。有没有解决方法?或者也许任何其他可以做类似事情的框架?
答案 0 :(得分:2)
您的methodToTest
来电a.getSomeField()
,但测试的设置部分并不期待这次通话。你想要这样的东西:
Foo foo = new Foo();
EasyMock.expect(mock.getSomeField()).andReturn(foo);
或者存根电话:
Foo foo = new Foo();
EasyMock.expect(mock.getSomeField()).andStubReturn(foo);
(在致电mock.getSomething()
之前)。
有关andReturn
和andStubReturn
之间的差异,请参阅this question。