[英]Ignore methods/void methods using EasyMock with Junit
“添加了更多详细信息”
我想模拟某种无效方法,但我不太确定该怎么做。 我读过有关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();
}
}
}
}
(编辑)谢谢。
对于返回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);
}
}
MainTest
测试updateCount是否在Updater
异常之外得到正确处理。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.