java - 如何在 JUnit 中测试 void 方法

标签 java junit

<分区>

如何使用 JUnit 测试 void 方法。

void add(int a, int b) {
 int c= a + b;
}

如何在Java中使用Junit测试上述方法。

最佳答案

如果方法有副作用,您可以在 JUnit 测试中检查它们。

在您的示例中,该方法没有副作用,因此无需测试

如果你还想测试它,你可以使用反射来这样做,但我认为这不是一个好的做法。

可以查看JUnit FAQ相关部分:

How do I test a method that doesn't return anything?

Often if a method doesn't return a value, it will have some side effect. Actually, if it doesn't return a value AND doesn't have a side effect, it isn't doing anything.

There may be a way to verify that the side effect actually occurred as expected. For example, consider the add() method in the Collection classes. There are ways of verifying that the side effect happened (i.e. the object was added). You can check the size and assert that it is what is expected:

@Test
public void testCollectionAdd() {
    Collection collection = new ArrayList();
    assertEquals(0, collection.size());
    collection.add("itemA");
    assertEquals(1, collection.size());
    collection.add("itemB");
    assertEquals(2, collection.size());
}

Another approach is to make use of MockObjects.

A related issue is to design for testing. For example, if you have a method that is meant to output to a file, don't pass in a filename, or even a FileWriter. Instead, pass in a Writer. That way you can pass in a StringWriter to capture the output for testing purposes. Then you can add a method (e.g. writeToFileNamed(String filename)) to encapsulate the FileWriter creation.

关于java - 如何在 JUnit 中测试 void 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16663597/

相关文章:

java - 如何在 Java 1.4 中向 XML 节点添加属性

Java代码找不到或定位指定的文件路径

java - 为什么我的测试失败?

java - Android jUnit 测试错误

java - ant项目中的单元测试

java - 如何在 Swing 中重新绘制而不清除窗口?

java - Parse.com Android API 和 Android 对话框

java - 通过@PersitenceContext 或@PersitenceUnit 注入(inject)一个EntityManagerFactory?

java - ant build.xml 中的 Junit Test 打印完整的堆栈跟踪,如何仅打印结果?

junit - 从 jacoco 分析中排除类方法