简体   繁体   English

如何使用同一junit测试多个Java文件?

[英]How can i test multiple java files with the same junit?

How can i test several .java files(that implements the same method in different ways) with one unit test? 如何通过一个单元测试来测试多个.java文件(以不同的方式实现相同的方法)? For example, i have a folder with different .java files(or different folders with the same name .java file), how can i select all of them to run it? 例如,我有一个文件夹,其中包含不同的.java文件(或具有相同名称的.java文件的不同文件夹),我该如何选择所有文件来运行它? right now i need to select each time one of them and move it to the same folder with the unit test and run it. 现在,我需要选择它们中的每一个,并将其移动到与单元测试相同的文件夹中并运行它。 Thanks. 谢谢。

Edit: I think i wasn't clear enough, so i will give more example: 编辑:我认为我还不够清楚,所以我将举更多的例子:

I have files aa.java and bb.java, which both have the method "static public int fibonacci(int x)", i want to create a unit test, that will use aa and bb methods and see if they work properly(assertEquals(result, expected)). 我有aa.java和bb.java文件,它们都具有“ static public int fibonacci(int x)”方法,我想创建一个单元测试,将使用aa和bb方法并查看它们是否正常工作(assertEquals (结果,预期))。 PS i have more then only 2 files with the same method. PS我只有两个文件,而且使用相同的方法。

Assuming you want to adhere to DRY , write a utility method to do the testing, and have a unit test(s) call it. 假设您要坚持使用DRY ,请编写一个实用程序方法来进行测试,并进行单元测试。

Eg 例如

private static void assertFibonacci(IntUnaryOperator op) {
    int n = 5;
    int expected = 8;
    // or a loop of values, whatever
    assert op.applyAsInt(n) == expected;
}

Then in your unit test: 然后在您的单元测试中:

@Test
public void testX() {
    assertFibonacci(new aa()::fibonacci);
    assertFibonacci(new bb()::fibonacci);
}

Or better, use separate Test methods, so errors in each are reported separately: 或者更好的是,使用单独的测试方法,因此每种方法中的错误都应分别报告:

@Test
public void testAA() {
    assertFibonacci(new aa()::fibonacci);
}

@Test
public void testBB() {
    assertFibonacci(new bb()::fibonacci);
}

The Spock Framework , which runs on top of JUnit, has much better support for parameterized testing , which is what you seem to want, than either plain JUnit or TestNG. 运行在JUnit之上的Spock框架比纯JUnit或TestNG对参数化测试 (您似乎想要的)的支持要好得多。

If you can't use Spock, you can either use JUnit Parameterized and supply an instance of each of your classes as your data set, or (my recommendation) write all your common unit tests in an abstract base class WidgetTests with a method protected abstract Widget getInstance() and subclass for each kind of widget. 如果您不能使用Spock,则可以使用JUnit Parameterized并提供每个类的实例作为数据集,或者(我的建议)将所有常见的单元测试写在抽象基类WidgetTests并使用方法protected abstract Widget getInstance()每种类型的小部件的protected abstract Widget getInstance()和子类。 This will still end up with multiple classes, but you won't repeat your test cases, and it allows you to write additional implementation-specific tests in an organized way. 这仍然会以多个类结束,但是您不会重复测试用例,它允许您以组织方式编写其他特定于实现的测试。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM