0

“添加了更多细节”

我想模拟某种 void 方法,但我不太确定如何去做。我阅读了有关 EasyMock 的信息,但我不知道当它是一个 void 方法时该怎么做,这是我的主要课程;

主班

public class Main {
    Updater updater = new Updater(main.getID(), main.getName(),....);

    try {
        updater.updateContent(dir);
    }

我想模拟updater.updateContent(dir); 一下,这样我就可以跳过尝试

更新程序类

private String outD;

public void updateContent(final String outDir) throws Exception {


    outD = outDir;
    if (...) {
        ....;
    }

}

...私有无效方法

到目前为止,这是我的测试课,

public class MainTest {


    @Before
    public void setUp() {

    }

    @Test
    public void testMain() { 


try {


        try {
            Updater updater = EasyMock.createNiceMock(Updater.class);
            updater.updateContent("/out");
            EasyMock.expectLastCall().andThrow(new RuntimeException()); 

            EasyMock.replay(updater);

            updater.updateContent("/out");
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } 


    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}


}
    }

(编辑)谢谢。

4

1 回答 1

1

对于返回 void 的方法,您必须以这种方式记录行为:

 Updater updater = EasyMock.createNiceMock(Updater.class);
 updater.updateContent("someDir"); // invoke the easy mock proxy and
 // after invoking it record the behaviour.
 EasyMock.expectLastCall().andThrow(new RuntimeException()); // for example

 EasyMock.replay(updater);

 updater.updateContent("someDir"); // will throw the RuntimeException as recorded

期待你有以下Main课程

public class Main {
    private Updater updater;

    private int updatedContentCount; // introduced for the example

    public Main(Updater updater) {
        this.updater = updater;
    }

    public void updateContent() {
        try {
            updater.updateContent("/out");
            updatedContentCount++;
        } catch (Exception e) {
            // skip for this example - normally you should handle this
        }
    }

    public int getUpdatedContentCount() {
        return updatedContentCount;
    }

}

你的更新程序的 API 看起来像这样

public class Updater {

    public void updateContent(String dir) throws Exception {
        // do something
    }
}

然后Main类的测试将是这样的:

public class MainTest {

    private Updater updater;
    private Main main;

    @Before
    public void setUp() {
        updater = EasyMock.createNiceMock(Updater.class);
        main = new Main(updater);
    }

    @Test
    public void testUpdateCountOnException() throws Exception {
        updater.updateContent("/out");
        EasyMock.expectLastCall().andThrow(new RuntimeException());
        EasyMock.replay(updater);
        main.updateContent();
        int updatedContentCount = main.getUpdatedContentCount();
        Assert.assertEquals(
                "Updated count must not have been increased on exception", 0,
                updatedContentCount);
    }
}

测试MainTestupdateCount 是否在Updater.

于 2013-10-24T10:56:55.740 回答