Weird problem using JUnit in multi-thread environment

前端 未结 5 1051
耶瑟儿~
耶瑟儿~ 2020-12-16 05:03

I meet a weired problem when using JUnit in multi-thread environment. The following code should fail, but it actually pass in eclipse.

public class ExampleT         


        
5条回答
  •  余生分开走
    2020-12-16 05:55

    @zjffdu As @ShiDoiSi pointed out, Thread.join() works fine if you have a single worker thread that you want to assert or fail from.

    If you have multiple worker threads, or if you want a little more convenience, there is a JUnit extension for performing multi-threaded assertions: ConcurrentUnit:

    public class ExampleTest extends ConcurrentTestCase {
        private ExecutorService executor = Executors.newFixedThreadPool(10);
    
        public void test() throws Throwable {
            executor.submit(new Runnable() {
                @Override
                public void run() {
                    try {
                        threadFail("Failure message");
                    } finally {
                        resume();
                    }
                }
            });
    
            threadWait();
        }
    }
    

    Good luck

提交回复
热议问题