Java JUnit测试与多线程

Java JUnit测试与多线程,java,multithreading,junit,Java,Multithreading,Junit,当基于非阻塞方案执行单个JUnit测试时,当测试方法终止其作用域时,所有线程都将被终止。比如说 @Test public void testMethod() { System.out.println("Before Running Thread"); Runnable runnable = new Runnable() { @Override public void run() { for(int index = 0

当基于非阻塞方案执行单个JUnit测试时,当测试方法终止其作用域时,所有线程都将被终止。比如说

@Test
public void testMethod() {

    System.out.println("Before Running Thread");

    Runnable runnable = new Runnable() {

        @Override
        public void run() {

            for(int index = 0; index <=1000; index++) {
                System.out.println("Current index: " + index);   
            }
        }

    };

    new Thread(runnable).start();

    System.out.println("After Running Thread");
}

现在让我们考虑在@方法之前建立的一个线程,假设一个以上的测试方法依赖于它的活动,例如:

class TestSuite {
Thread importantThread;

    @Before
    public void beforeTest(){
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                for(int index = 0; index <=1000; index++) {
                    System.out.println("Current index: " + index);   
                }
            }
        };
        importantThread = new Thread(runnable);
        importantThread.start();
    }

    @Test
    public void testOne {
        // Some action
    }

    @Test
    public void testTwo() {
        // Some action
    }

}
类测试套件{
线程重要线程;
@以前
测试前公共无效(){
Runnable Runnable=新的Runnable(){
@凌驾
公开募捐{

对于(int index=0;index如果它依赖于这样的外部线程,那么它不是一个很好的单元测试,因此即使你能让它工作,你也应该修复你的设计。线程负责什么,为什么它在你的测试工具中运行?可能的重复。如果你能解释为什么你的测试,你可能会得到更多/更好的帮助需要这些线程。很有可能有人会引导您采用更好的测试方法,或者更易于测试的系统设计。
class TestSuite {
Thread importantThread;

    @Before
    public void beforeTest(){
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                for(int index = 0; index <=1000; index++) {
                    System.out.println("Current index: " + index);   
                }
            }
        };
        importantThread = new Thread(runnable);
        importantThread.start();
    }

    @Test
    public void testOne {
        // Some action
    }

    @Test
    public void testTwo() {
        // Some action
    }

}