mt2*_*t22 8 java testing junit multithreading unit-testing
在标题中,我想测试这样的方法:
public void startThread()
{
new Thread()
{
public void run()
{
myLongProcess();
}
}.start();
}
Run Code Online (Sandbox Code Playgroud)
编辑:通过评论判断我认为测试线程是否启动并不常见.所以我要调整问题......如果我的要求是100%的代码覆盖率,我是否需要测试该线程是否启动?如果是这样,我真的需要一个外部框架吗?
这可以通过Mockito优雅地完成.假设该类已命名,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();
}
Run Code Online (Sandbox Code Playgroud)