开发者

Java ThreadFactory how to create ThreadCreationException for testing in JUnit

Trying to create a unit test (borderline integration testing) using开发者_开发知识库 ThreadFactory, and just wondering how do I 'force' Java/JVM to not being able to create more threads ?

In other words how do I call ThreadFactory.newThread and get null ?

import org.jboss.threads.JBossThreadFactory.JBossThreadFactory;  
import java.util.concurrent.ThreadFactory;

private final ThreadFactory threadFactory;

JBossThreadFactory threadFactory = new JBossThreadFactory(null, null, null, "test thread %p %t", null, null);

final Thread thread = threadFactory.newThread(new Worker(task));
if (thread == null) {
    throw new ThreadCreationException();
}


If you are using dependency injection, then you could create a mock ThreadFactory:

private class NullThreadFactory implements ThreadFactory {
    public Thread newThread(Runnable r) {
        return null;
    }
}

and inject use the NullThreadFactory instead of the JBossThreadFactory for that particular unit test.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜