如何使用带有使用Spring注入的字段的参数化JUnit测试运行器?

Edw*_*ale 19 java junit spring

我正在使用Spring将目录的路径注入到我的单元测试中.在这个目录里有一些应该用来生成使用参数化测试用例的测试数据文件的参数测试运行.不幸的是,测试运行器要求提供参数的方法是静态的.这对我的情况不起作用,因为目录只能注入非静态字段.我有什么想法可以解决这个问题吗?

Sim*_* LG 11

您可以使用Spring的TestContextManager.在这个例子中,我使用Theories而不是Parameterized.

@RunWith(Theories.class)
@ContextConfiguration(locations = "classpath:/spring-context.xml")
public class SeleniumCase {
  @DataPoints
  public static WebDriver[] drivers() {
    return new WebDriver[] { firefoxDriver, internetExplorerDriver };
  }

  private TestContextManager testContextManager;

  @Autowired
  SomethingDao dao;

  private static FirefoxDriver firefoxDriver = new FirefoxDriver();
  private static InternetExplorerDriver internetExplorerDriver = new InternetExplorerDriver();

  @AfterClass
  public static void tearDown() {
    firefoxDriver.close();
    internetExplorerDriver.close();
  }

  @Before
  public void setUpStringContext() throws Exception {
    testContextManager = new TestContextManager(getClass());
    testContextManager.prepareTestInstance(this);
  }

  @Theory
  public void testWork(WebDriver driver) {
    assertNotNull(driver);
    assertNotNull(dao);
  }
}
Run Code Online (Sandbox Code Playgroud)

我在这里找到了这个解决方案:如何使用Spring进行参数化/理论测试


Jea*_*sky 7

我假设您使用的是JUnit 4.X,因为您提到了参数化测试运行器.这意味着你没有使用@RunWith(SpringJUnit4ClassRunner).不是问题,只列出我的假设.

以下使用Spring从XML文件中获取测试文件目录.它不会注入它,但数据仍然可用于您的测试.并且在静态方法中也不逊色.

我看到的唯一缺点是它可能意味着你的Spring配置被多次解析/配置.如果需要,您可以只加载具有测试特定信息的较小文件.

@RunWith(Parameterized.class)
public class MyTest {
    @Parameters
    public static Collection<Object[]> data() {
        ApplicationContext ctx = new ClassPathXmlApplicationContext("/jeanne/jeanne.xml");
        String dir = ctx.getBean("testFilesDirectory", String.class);

            // write java code to link files in test directory to the array
        return Arrays.asList(new Object[][] { { 1 } });
    }
// rest of test class
}
Run Code Online (Sandbox Code Playgroud)


Abh*_*kar 5

对于那些在2015年末或之后阅读的人来说,除了SpringJUnit4ClassRunner之外,Spring 4.2还增加了SpringClassRule和SpringMethodRule,它们利用了对Spring TestContext Framework的支持.

这意味着像任何亚军一流的支持MockitoJUnitRunnerParameterized:

@RunWith(Parameterized.class)
public class FibonacciTest {
    @ClassRule public static final SpringClassRule SCR = new SpringClassRule();
    @Rule public final SpringMethodRule springMethodRule = new SpringMethodRule();

    long input;
    long output;

    public FibonacciTest(long input, long output) { this.input = input; ...} 

    @Test
    public void testFibonacci() {
        Assert.assertEquals(output, fibonacci(input));
    }

    public List<Long[]> params() {
        return Arrays.asList(new Long[][] { {0, 0}, {1, 1} });
    }
}
Run Code Online (Sandbox Code Playgroud)