2
可以說我有以下代碼:
嘲笑對象類如何初始化模擬對象?
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是不是像我想要的初始化。有什麼解決方法嗎?或者可能有其他的框架可以做到這一點?
你是對的我忘了測試它。但事實並非如此。問題是你可以看到我的構造函數初始化'someField',並且當我進行模擬時,'someField'爲空,結果整個'methodToTest'中斷。那意味着構造函數沒有被調用? – randomUser56789
@ su234fk234hawuhsafklsfjs:你的*正常*實現做什麼是無關緊要的。你在嘲笑那個班級,所以它的行爲並不重要。只要你嘲笑你正在做的調用,以便'getSomeField()'返回一個非空引用,這沒關係。 –
但問題是'getSomeField();'返回null,因爲'SomeClass'初始化'someField'沒有別的也沒有setter。我不明白如果通過'b.do();' – randomUser56789