简体   繁体   English

如何编写创建新线程的单元测试

[英]How to write unit test which creates new thread

I have following method for test: 我有以下测试方法:

public class classToTest{
    @Autowired
    private Alternator alternator;

     public void methodToTest(){
         Thread t = new Thread(new Runnable() {
             public void run() {
                 while(true) {
                     if(alternator.get()) {
                         System.out.print("Hello");
                         alternator.set(false);
                     }
                 }
             }
          };
          t.start()
    }
}

I need to check that was invoked method 我需要检查那是被调用的方法

alternator.set(false);

How can I do it? 我该怎么做?

Instead of starting a thread directly, can you pass in an "Executor" instance? 您可以传入“Executor”实例,而不是直接启动线程吗?

For example... 例如...

public class ClassToTest{
    @Autowired
    private Alternator alternator;

    @Autowired @Qualifier("myExecutor")
    private java.util.concurrent.Executor executor;

    public void methodToTest() {
        Runnable runnable = new Runnable() {
           public void run() {
               while(true) {
                 if(alternator.get()) {
                     System.out.print("Hello");
                     alternator.set(false);
                 }
             }
        };

        executor.execute(runnable);
    }
}

Now you can test this easier... 现在你可以更轻松地测试这个......

public class ClassToTestTest {

    ...

    @Before
    public void setup() {
        alternator = mock(Alternator.class);
        executor = mock(Executor.class);

        obj = new ClassToTest();
        ReflectionTestUtils.setField(obj, "alternator", alternator);
        ReflectionTestUtils.setField(obj, "executor", executor);
    }

    @Test
    public void shouldStartRunnable() {
        obj.methodToTest();

        ArgumentCaptor<Runnable> runnableCaptor = ArgumentCaptor.forClass(Runnable.class);

        verify(executor).execute(runnableCaptor.capture());

        Runnable runnable = runnableCaptor.getValue();

        // Now test your actual "runnable"...
        when(alternator.get()).thenReturn(true);
        runnable.run();

        verify(alternator).set(false);
    }
}

(Have not tried to compile this, so I apologise if there are any mistakes!!) (没有尝试编译这个,所以如果有任何错误,我道歉!!)

Though Bret's post of passing in an executor is very much recommended, you can use the timeout() mock verification setting to test for asynchronous conditions. 虽然非常推荐Bret的传入执行程序的帖子 ,但您可以使用timeout()模拟验证设置来测试异步条件。

verify(alternator, timeout(500)).set(false);

Note that this will necessarily increase the flakiness of your test (ie the likelihood that the test fails when the code passes). 请注意,这必然会增加测试的瑕疵(即代码通过时测试失败的可能性)。 With a sensible timeout value, that flakiness should be negligible, but if you're making this a part of your core test infrastructure you may consider refactoring to allow for synchronous execution in the test. 使用合理的超时值,这种松散度应该可以忽略不计,但如果您将其作为核心测试基础架构的一部分,则可以考虑重构以允许在测试中同步执行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何为一种方法编写单元测试,该方法可以动态创建数据库表? - How to write a unit test for a method, which creates database table on the fly? 如何对创建新对象的类进行单元测试 - how to unit test a class which creates new objects 如何为创建表和添加值的方法编写测试用例 - How to write a test case for method which creates the table and add values 如何为未捕获的线程异常处理程序编写单元测试。 - How to write a unit test for an uncaught thread exception handler. 如何对需要时间执行操作的线程进行单元测试 - How to Unit-Test Thread which takes time to perform action 如何单元测试ExecutorService为任务生成新线程? - How to unit test that ExecutorService spawns new thread for task? 如何编写单元测试? - How to write a Unit Test? 如何为在其中创建对象并将其传递给模拟对象的方法编写单元测试? - How to write a unit test for method that creates an object inside of it and passes it to mocked object? Spock -Unit Test:如何为需要 Mono 的 @around 注释编写 spock 单元测试 - Spock -Unit Test:How to write spock unit test for @around annotation which takes Mono 如何编写单元测试以测试Thread.Sleep的功能? - How can I write a unit test to test the functionality of Thread.Sleep?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM