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 没有像我想要的那样初始化。有什么解决方法吗?或者也许任何其他可以做类似事情的框架?

4

1 回答 1

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())。

有关 和之间的区别,请参阅此问题andReturnandStubReturn

于 2013-02-06T19:35:33.423 回答