【问题标题】:SpringJUnit4ClassRunner: run test method multiple times with different input dataSpringJUnit4ClassRunner:使用不同的输入数据多次运行测试方法
【发布时间】:2015-03-22 12:12:03
【问题描述】:

我正在为 Spring 应用程序开发测试。我有几个测试要针对不同的数据运行多次。

我不能使用 JUnit 的 @Parameters,因为必须使用 Parameterized.class 运行测试类才能使其工作,而我必须使用设置模拟 Spring 上下文的 SpringJUnit4ClassRunner.class 运行测试类。 不幸的是,似乎this runner doesn't support processing of the @Parameters annotation。我也看了一下TestContextBootstrapper和TextExecutionListener,但是好像也帮不了我。

有没有办法为不同的输入数据多次运行 Spring 应用程序的测试?

我需要类似于 TestNG 的 @Test(dataProvider=) @DataProvider couple 或 @Factory(dataProvider = ) @DataProvider couple。

提前致谢。

【问题讨论】:

    标签: java spring spring-mvc junit junit4


    【解决方案1】:

    如果你可以依赖 JUnit 4.12,你可以使用 Parameterized@UseParametersRunnerFactory

    首先,创建一个实现ParameterizedRunnerFactory 的类,返回您要运行测试的Runner 的实例:

    public class SpringJUnit4ClassRunnerFactory
        implements ParameterizedRunnerFactory {
      @Override
      public Runner createRunnerForTestWithParameters(final TestWithParameters test)
             throws InitializationError {
         return new SpringJUnit4ClassRunner(testClass.getJavaClass()) {
           @Override
           protected Object createTest() throws Exception {
             Object[] args = test.getParameters().toArray();
             Object testInstance = test.getTestClass().getOnlyConstructor()
                 .newInstance(args);
    
             // copied from SpringJUnit4ClassRunner.createTest():
             getTestContextManager().prepareTestInstance(testInstance);
             return testInstance;
           }
         };
      }
    }
    

    然后你可以用@UseParametersRunnerFactory注释你的测试类:

    @UseParametersRunnerFactory
    @RunWith(Parameterized.class)
    public class FooTesdt {
    }
    

    详情请见the Parameterized Javadoc

    【讨论】:

    • 所以我需要用Parameterized运行我的测试类,用@UseParametersRunnerFactory指定工厂,这个工厂必须返回一个SpringJUnit4Runner的子类(用接受TestWithParameters的构造函数扩展)和@987654332 TestWithParameters 的 @ 方法必须返回将传递给我的测试类的构造函数的参数列表?
    【解决方案2】:

    找到了一个更简单的解决方案here

    将发布哪些解决方案对我有用。

    【讨论】:

      猜你喜欢
      • 2013-06-13
      • 2014-02-19
      • 2010-10-19
      • 1970-01-01
      • 2018-10-10
      • 2017-03-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多