java - 将线程局部变量传递给 JUnit 测试

标签 java junit thread-local parameterized-unit-test

我有一个线程,它初始化线程局部类变量并从运行单元测试开始:

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/

相关文章:

java - apache tomcat问题-404错误

java - cloudbees 和 ESAPI - 如何指向 ESAPI 目录?

android - 为什么我使用 sendKeys() 的测试在 Android 模拟器中没有动画?

java - 如何在 Android JUnit 测试中测试文本框的值

Java 声明/变量作用域问题

c# - Java 等效于 C# 的 HttpContext.Current.Items.set/get

spring boot 测试错误的配置类

.net - .NET 中的本地可继承线程

multithreading - Pharo Smalltalk 中的 ThreadLocal 类

multithreading - 使用 NIO 或 Netty 等事件驱动框架时如何跟踪请求过程