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