junit assert in thread throws exception

后端 未结 5 1392
再見小時候
再見小時候 2020-12-28 15:10

What am I doing wrong that an exception is thrown instead of showing a failure, or should I not have assertions inside threads?

 @Test
 public void testCompl         


        
5条回答
  •  抹茶落季
    2020-12-28 15:56

    A small improvement to Eyal Schneider's answer:
    The ExecutorService allows to submit a Callable and any thrown Exceptions or Errors are rethrown by the returned Future.
    Consequently, the test can be written as:

    @Test
    public void test() throws Exception {
      ExecutorService es = Executors.newSingleThreadExecutor();
      Future future = es.submit(() -> {
        testSomethingThatMightThrowAssertionErrors();
        return null;
      });
    
      future.get(); // This will rethrow Exceptions and Errors as ExecutionException
    }
    

提交回复
热议问题