简体   繁体   English

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

[英]How to load a different resource with different unit test methods?

I have about 15 JUnit test cases each one which needs a difference resource file from which it reads necessary input data. 我大约有15个JUnit测试用例,每个用例都需要一个差异资源文件,从该文件中读取必要的输入数据。 Currently, I'm hard coding the specific resource file path in each test case method. 当前,我正在每种测试案例方法中对特定的资源文件路径进行硬编码。

@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
}

May be I could have all these files loaded in the setUp() method into separate URL variables and then use the specific URL variable in each test method. 可能是我可以将所有这些文件都通过setUp()方法加载到单独的URL变量中,然后在每个测试方法中使用特定的URL变量。 Is there a way better way of doing this? 有没有更好的方法可以做到这一点?

You can use the TestName rule. 您可以使用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
}

Try JUnit RunWith(Parameterized.class) . 试试JUnit RunWith(Parameterized.class)

Example, that takes a resource name and an int expected result : 示例,它带有一个资源名称和一个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
    }

}

More info here: http://junit.org/apidocs/org/junit/runners/Parameterized.html 此处的更多信息: http : //junit.org/apidocs/org/junit/runners/Parameterized.html

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

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