我有一个线程,它初始化线程局部类变量并从运行单元测试开始:
public class FooThread extends Thread {
TestRunner runner;
Foo foo;
public void run() {
initSomeThreadLocalStuff(); // inits foo and runner
runner.runJUnitTests(); // JUnitCore.runTest(TestClass)
}
private void initSomeThreadLocalStuff() {
foo = new Foo(this);
// ...
}
}
public class Foo() {
public Foo(FooThread t) {
// ...
}
}
现在我想通过访问(或引用)线程本地对象 foo
来运行 JUnit 测试。这可能吗?我试图保持简单,但复杂的事情似乎不太清楚(所以我添加了一些代码):Foo 对象需要当前的 FooThread 来初始化。
最佳答案
看起来像 JUnit parameterized unit tests这就是您正在寻找的。
编辑:基于 JUnit wiki 上提供的示例的示例代码:
@RunWith(Parameterized.class)
public class Test {
@Parameters
public static Collection<Object[]> data() {
return Arrays.asList(new Object[][] {{ new ThreadLocalProvider() }});
}
@Parameter(value = 0) // first data value (0) is default
public /* NOT private */ ThreadLocalProvider tloProvider;
public ThreadLocal<Object> tlo;
@Before
public void setup() {
// getNew() will be called in the same thread in which the unit test will run.
tlo = tloProvider.getNew();
}
@Test
public void test() {
// Test using tlo.
}
}
class ThreadLocalProvider {
public ThreadLocal<Object> getNew() {
// Instantiate a *new* ThreadLocal object and return it.
}
}
注意:如果您使用提供程序,您也可以在不使用参数化运行程序的情况下运行测试(只需在 @Before
方法中从提供程序获取一个新对象),但由于我不太了解您的代码或要求,因此我将这个选择留给您。
此外,您不需要实例化自己的 JUnit Runner。您可以使用 JUnit ( reference ) 提供的 Runner
以及 @RunWith
注释。
关于java - 将线程局部变量传递给 JUnit 测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27901391/