我知道有一些关于void-method Unit-Testing的问题,但我的问题是不同的.
我正在学习java,所以我的老板给了我一些对我的任务有不同要求的任务.
在我的实际任务中,有一个要求,即jUnit测试必须覆盖> 60%.所以我需要测试一种非常简单的方法来达到这个60%.方法如下:
public void updateGreen() {
// delete this outprint if the Power Manager works
System.out.println(onCommand + "-green");
// p = Runtime.getRuntime().exec(command + "-green");
// wait until the command is finished
// p.waitFor();
}
Run Code Online (Sandbox Code Playgroud)
由于实习问题,我无法用Runtime任务执行命令.所以System.out这种方法只有一个.
我有多种方法,因此这种方法的测试将覆盖整个代码的10%以上.
测试这种方法有用吗?什么时候,怎么样?
And*_*hev 10
如果有很多这样的方法,那么你可能想要在这里测试的是updateScreen()使用正确的字符串,"some-command-green"并且System.out正在调用它.为了做到这一点,你可能想要提取System.out到一个对象字段并模拟它(即用Mockito的spy())来测试提供给它的字符串println.
即
class MyClass{
PrintStream out = System.out;
public void updateGreen() { ... }
}
Run Code Online (Sandbox Code Playgroud)
在测试中:
@Test
public void testUpdate(){
MyClass myClass = new MyClass();
myClass.out = Mockito.spy(new PrintStream(...));
// mock a call with an expected input
doNothing().when(myClass.out).println("expected command");
myClass.updateGreen();
// test that there was a call
Mockito.verify(myClass.out, Mockito.times(1)).println("expected command");
}
Run Code Online (Sandbox Code Playgroud)