Java 如何在jUnit中测试一个非常简单的void方法?
我知道关于void方法单元测试有几个问题,但我的问题不同。Java 如何在jUnit中测试一个非常简单的void方法?,java,junit,Java,Junit,我知道关于void方法单元测试有几个问题,但我的问题不同。 我正在学习java,所以我的老板给了我一些对我的任务有不同要求的任务 在我的实际任务中,有一个要求,即jUnit测试必须覆盖>60%。所以我需要测试一个非常简单的方法来达到60%。方法如下: public void updateGreen() { // delete this outprint if the Power Manager works System.out.println(onCommand + "-gree
我正在学习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();
}
由于实习生问题,我无法使用运行时任务执行命令。因此,在这种方法中只有一个系统.out
我有很多这样的方法,所以这个方法的测试将覆盖我全部代码的10%以上
测试这种方法有用吗?如果是,如何返回?如果方法成功运行,则返回true,否则返回false。这很容易测试
您还可以测试此方法的输出,如下所述:
但根据我的经验,让方法返回乐观或悲观的值(真/假、1/0/-1等)来指示其状态要好得多
还可以为onCommand标志编写getter方法:
public string getFlag(){
// some logic here
return "green";
// otherwise default to no flags
return "";
}
如果有很多这样的方法,您可能希望在这里测试的是updateScreen()
使用正确的字符串“some command green”,并且正在调用System.out
。为此,您可能需要将System.out
提取到对象字段中,并对其进行模拟(即使用Mockito的spy()
),以测试提供给println
的字符串
即
在测试中:
@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");
}
您可以使用您想进行什么单元测试来测试onCommand+“-green”
是否已写入System.out
?updateGreen()
是调用Runtime.exec()
还是调用实际结果?不知道Mockito。现在读一读。看起来真的很棒。正如我所搜索的。是的,模拟很简单,但在单元测试中很重要。很高兴听到你喜欢它。
@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");
}