如何使用不同的单元测试方法加载不同的资源?

How to load a different resource with different unit test methods?

我有大约 15 个 JUnit 测试用例,每个测试用例都需要一个不同的资源文件,从中读取必要的输入数据。目前,我正在对每个测试用例方法中的特定资源文件路径进行硬编码。

@Test
public void testCase1() {
    URL url = this.getClass().getResource("/resource1.txt");
        // more code here
}

@Test
public void testCase2() {
    URL url = this.getClass().getResource("/resource2.txt");
        // more code here
}

也许我可以在 setUp() 方法中将所有这些文件加载​​到单独的 URL 变量中,然后在每个测试方法中使用特定的 URL 变量。有更好的方法吗?

您可以使用 TestName 规则。

@Rule public TestName testName = new TestName();
public URL url;

@Before
public void setup() {
    String resourceName = testName.getMethodName().substring(4).toLowerCase();
    url = getClass().getResource("/" + resourceName + ".txt");
}

@Test
public void testResource1() {
    // snip
}

@Test
public void testResource2() {
    // snip
}

试试 JUnit RunWith(Parameterized.class)

示例,采用资源名称和 int 预期结果:

@RunWith(Parameterized.class)

public class MyTest {

    @Parameterized.Parameters
    public static Collection<Object[]> data() {
        return Arrays.asList(new Object[][]{
            {"resource1.txt", 0000}, {"resource2.txt", 9999}
        });
    }

    public final URL url;
    public final int expected;

    public MyTest(String resource, int expected) {
        this.url=URL url = this.getClass().getResource("/"+resource)
        this.expected = expected;
    }

    @Before
    public void setUp() {
    }

    @Test
    public void testReadResource() throws Exception {
        // more code here, based on URL and expected
    }

}

更多信息在这里:http://junit.org/apidocs/org/junit/runners/Parameterized.html