junit assert in thread throws exception

后端 未结 5 1381
再見小時候
再見小時候 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:48

    I ended up using this pattern it work with both Runnables and Threads. It is largely inspired from the answer of @Eyal Schneider:

    private final class ThreadUnderTestWrapper extends ThreadUnderTest {
        private Exception ex;
    
        @Override
        public void run() {
            try {
                super.run();
            } catch ( Exception ex ) {
                this.ex = ex;
            }
        }
    
        public Exception getException() throws InterruptedException {
            super.join(); // use runner.join here if you use a runnable. 
            return ex;
        }
    }
    
    0 讨论(0)
  • 2020-12-28 15:50

    Where multiple worker threads are concerned, such as in the original question, simply joining one of them is not sufficient. Ideally, you'll want to wait for all worker threads to complete while still reporting assertion failures back to the main thread, such as in Eyal's answer.

    Here's a simple example of how to do this using ConcurrentUnit:

    public class MyTest extends ConcurrentTestCase {
        @Test
        public void testComplex() throws Throwable {
            int loops = 10;
            for (int i = 0; i < loops; i++) {
                new Thread(new Runnable() {
                    public void run() {
                        threadAssertEquals(1, 1);
                        resume();
                    }
                }).start();
            }
    
            threadWait(100, loops); // Wait for 10 resume calls
        }
    }
    
    0 讨论(0)
  • 2020-12-28 15:54

    The JUnit framework captures only assertion errors in the main thread running the test. It is not aware of exceptions from within new spawn threads. In order to do it right, you should communicate the thread's termination state to the main thread. You should synchronize the threads correctly, and use some kind of shared variable to indicate the nested thread's outcome.

    EDIT:

    Here is a generic solution that can help:

    class AsynchTester{
        private Thread thread;
        private AssertionError exc; 
    
        public AsynchTester(final Runnable runnable){
            thread = new Thread(new Runnable(){
                public void run(){
                    try{            
                        runnable.run();
                    }catch(AssertionError e){
                        exc = e;
                    }
                }
            });
        }
    
        public void start(){
            thread.start();
        }
    
        public void test() throws InterruptedException{
            thread.join();
            if (exc != null)
                throw exc;
        }
    }
    

    You should pass it the runnable in the constructor, and then you simply call start() to activate, and test() to validate. The test method will wait if necessary, and will throw the assertion error in the main thread's context.

    0 讨论(0)
  • 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
    }
    
    0 讨论(0)
  • JUnit throws AssertionError that extends of Throwable, it has the same parent of Exception. You can catch the fail assert of the thread, then save in a static field and finally check in the main thread if the other thread has failed some assert.

    First, create the static field

    private volatile static Throwable excepcionTE = null;
    

    Second, wrap the asserts in a try/catch and catch AssertionError

            try
        {
          assertTrue("", mensaje.contains("1234"));
        }
        catch (AssertionError e)
        {
          excepcionTE = e;
          throw e;
        }
    

    And finally, check in the main thread that field

     if (excepcionTE != null)
    {
      excepcionTE.printStackTrace();
      fail("Se ha producido una excepcion en el servidor TE: "
          + excepcionTE.getMessage());
    }
    
    0 讨论(0)
提交回复
热议问题