Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/343.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何在jUnit中测试一个非常简单的void方法?_Java_Junit - Fatal编程技术网

Java 如何在jUnit中测试一个非常简单的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

我知道关于void方法单元测试有几个问题,但我的问题不同。
我正在学习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");
}