Junit测试用例构造函数在参数化运行器中调用 [英] Junit Test Case constructor calls in parameterized runner

查看:77
本文介绍了Junit测试用例构造函数在参数化运行器中调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了一个很长的参数化测试,其中一个参数是带有双花括号语法的构造函数调用,以为2D数组的每一行构造一个不同的对象:

I wrote a long parameterized test, one of whose parameters is a constructor call with double-brace syntax to construct a different object for each row of the 2D array:

Object[][] data = new Object[][] {
{ 1, 2, 3, new Blah() {{ setA(); }} }
{ 1, 2, 3, new Blah() {{ setB(); }} }
...

由于JUnit的理念是在每个@Test上调用测试用例构造函数,因此我假设它在参数化测试中将执行相同的操作-但我看到它仅在调用该构造函数(为参数化测试),每行一次,而不是每行一次.

Since the philosophy of JUnit is to call the test case constructor on each @Test, I was assuming that it would do the same with parameterized tests - but I'm seeing that it's only calling that constructor (the constructor defined for the parameterized test) once per row, not once per test per row.

因此,测试字段在全局范围内运行,并且测试相互影响.我想知道是否有一种方法可以像常规JUnit运行器那样强制运行器为每个测试调用构造函数.Google和JUnit页面在这种情况下对我没有帮助.我真的不希望重写整个测试,因为到目前为止,该测试是广泛的并且可读性很强.

So, the test fields are behaving globally and tests are affecting each other. I want to know if there's a way to force the runner to call the constructor for each tests, as with the regular JUnit runner. Google and the JUnit pages are not helping me on this case. I'd really rather not rewrite the entire test, which is extensive and fairly readable at this point.

推荐答案

我不确定我是否会完全关注您,但是运行测试时,会发生以下情况:

I'm not sure if I completely follow you but when the test is run, this is what happens:

  1. 用@Parameters方法注释的方法仅被调用一次.
  2. 为带注释的方法返回的集合中的每一行创建一个测试运行器实例.
  3. 使用其构造函数为参数集合中的每一行实例化测试 ,但该测试将传递到从初始调用中缓存的相应参数值行中.
  1. The method you've annotated with @Parameters method is called once and only once.
  2. A test runner instance is created for each row in the collection returned by the annotated method.
  3. The test is instantiated for each row in the parameter collection using its constructor, but it is passed in the corresponding parameter value row that was cached from the initial invocation.

通过单击此处此处.如果您要在两次调用之间改变状态(使用静态方法或其他方法),则可能会看到怪异的东西.

You can see where this happens by clicking here and here. If you're mutating state between calls (using a static method or whatever) expect to see weird things.

仔细阅读代码后,我对您现在要问的内容有了更好的了解.我刚刚使用JUnit 4.10调试了参数化测试,并且确实确实每次测试每行调用一次构造函数.

After poking around in the code, I understand better what you're asking now. I've just debugged a parameterized test using JUnit 4.10 and it does indeed invoke the constructor once per row per test.

这篇关于Junit测试用例构造函数在参数化运行器中调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆