简体   繁体   English

如何对使用jUnit简单启动线程的方法进行单元测试?

[英]How to unit test a method that simply starts a thread with jUnit?

As in the title, I want to test a method like this: 在标题中,我想测试这样的方法:

public void startThread()
{
    new Thread()
    {
        public void run()
        {
            myLongProcess();
        }
    }.start();
}

EDIT: Judging by comments I guess it is not very common to test if a thread starts or not. 编辑:通过评论判断我认为测试线程是否启动并不常见。 So I've to adjust the question... if my requirement is 100% code coverage do I need to test if that thread starts or not? 所以我要调整问题......如果我的要求是100%的代码覆盖率,我是否需要测试该线程是否启动? If so do I really need an external framework? 如果是这样,我真的需要一个外部框架吗?

This can be done elegantly with Mockito . 这可以通过Mockito优雅地完成。 Assuming the class is named ThreadLauncher you can ensure the startThread() method resulted in a call of myLongProcess() with: 假设该类名为ThreadLauncher您可以确保startThread()方法导致调用myLongProcess()

public void testStart() throws Exception {
    // creates a decorator spying on the method calls of the real instance
    ThreadLauncher launcher = Mockito.spy(new ThreadLauncher());

    launcher.startThread();
    Thread.sleep(500);

    // verifies the myLongProcess() method was called
    Mockito.verify(launcher).myLongProcess();
}

If you need 100% coverage, you will need to call startThread which will kick off a thread. 如果你需要100%的覆盖率,你需要调用startThread来启动一个线程。 I recommend doing some sort of verification that the thread was stared (by verifying that something in myLongProcess is happening, then clean up the thread. Then you would probably do the remainder of the testing for myLongProcess by invoking that method directly from your unit test. 我建议进行某种验证线程被盯着(通过验证myLongProcess中的某些myLongProcess正在发生,然后清理线程。然后你可能会通过直接从你的单元测试中调用该方法来完成myLongProcess的剩余测试。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM