10

如标题所示,我想测试这样的方法:

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

编辑:从评论来看,我猜测试线程是否启动并不常见。所以我必须调整问题......如果我的要求是 100% 的代码覆盖率,我是否需要测试该线程是否启动?如果是这样,我真的需要一个外部框架吗?

4

2 回答 2

7

这可以使用Mockito优雅地完成。假设该类已命名ThreadLauncher,您可以确保该startThread()方法导致调用myLongProcess()with:

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();
}
于 2012-06-18T10:08:54.380 回答
1

If you need 100% coverage, you will need to call startThread which will kick off a thread. 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.

于 2012-06-18T13:31:10.880 回答