使用JUnit,您可以使用@RunWith(Parameterized.class)
来提供一组参数传递给测试构造函数,然后对每个对象运行测试。混合参数化和程序化单元测试
我试图将尽可能多的测试逻辑移入数据中,但有一些测试不会轻易转换为数据驱动的测试。有没有办法使用JUnit的Parameterized
runner来运行一些带参数的测试,然后添加非数据驱动的测试,这些测试对于每个测试对象构造都不会重复运行?
使用JUnit,您可以使用@RunWith(Parameterized.class)
来提供一组参数传递给测试构造函数,然后对每个对象运行测试。混合参数化和程序化单元测试
我试图将尽可能多的测试逻辑移入数据中,但有一些测试不会轻易转换为数据驱动的测试。有没有办法使用JUnit的Parameterized
runner来运行一些带参数的测试,然后添加非数据驱动的测试,这些测试对于每个测试对象构造都不会重复运行?
我的解决方法是创建一个类,并将编程和数据驱动的测试放在两个单独的子类中。 JUnit运行测试时,子类必须是静态的。这是一个骨架:
@RunWith(Enclosed.class) // needed for working well with Ant
public class MyClassTests {
public static class Programmatic {
@Test
public void myTest(){
// test something here
}
}
@RunWith(Parameterized.class)
public static class DataDriven {
@Parameters
public static Collection<Object[]> getParams() {
return Collections.emptyList();
}
private String data;
public DataDriven(String testName, String data){
this.data = data;
}
@Test
public void test() throws AnalyzeExceptionEN{
// test data string here
}
}
}
一种方法是使用Junit的Enclosed
跑步者。它非常冗长,但也非常强大。它允许你在一个文件中组合多个不同的跑步者。
其他选项是使用自定义junit亚军。肯定zohhak支持tests with parameters and without。小提取物:
@RunWith(ZohhakRunner.class)
public class CoercingTest {
@TestWith("ONE_OF_ENUM_VALUES")
public void should_coerce_enum(SampleEnum param) {
assertThat(param).isEqualTo(SampleEnum.ONE_OF_ENUM_VALUES);
}
@Test
public void should_run_standard_junit_test() {
//this will also work
}
}
如果它对你来说还不够,肯定你可以找到其他支持这两种测试的跑步者。
有2个测试类有什么问题?一个用于参数化,一个用于非参数化? – dkatzel
我宁愿在一次测试中为一个类进行测试,而不是创建“MyClassDataDrivenTest”和“MyClassProgrammaticTest”。 –