Testing several threads to catch Java exception



  • We are testing the code and we know that we should have an exception thrown. For example, we are testing an iterator and we know that there are no more elements, and if we call next (), then we get a NoSuchElementException, and so everything is fine, we write:

    @Test (expected = NoSuchElementException.class)
    public void shoulThrowNoSuchElementException () {
         it = new Iteratorrmatrixmass (new int [] [] {});
         it.next ();
    }
    

    We have several threads and one of the threads should throw an OptimisticException:

    @Test (expected = OptimisticException.class)
        public void update () throws InterruptedException {
            Base base = new Base (1, 1, "12321");
            Base base1 = new Base (1, 2, "");
            СacheBase data = new СacheBase ();
            data.add (base);
            Thread r1 = new Thread (new Update (data, base1), "r1");
            Thread r2 = new Thread (new Update (data, base1), "r2"); // OptimisticException.class should be here
            r1.start ();
            r2.start ();
            r1.join ();
            r2.join ();
            System.out.println (base.getVersion ());
        }
    

    But in this case (expected = OptimisticException.class) this did not help us, in the console the inscription will still pop up:

    Exception in thread "r2" ru.job4j.blockhash.OptimisticException: The object has already been updated to the current version, the update was refused
    

    I suppose this exception is not popping up on the main thread. What should be done to make the test successful?



  • There is a working solution:

    @Test
         public void test () {
    
         CompletableFuture <Void> future = CompletableFuture.runAsync (() -> {
             throw new OptimisticException ("Optimistic exception"); // your executable code
         });
    
         assertThatThrownBy (future :: get)
                 .hasCauseExactlyInstanceOf (OptimisticException.class)
                 .hasMessageContain ("Optimistic Exception");
        }
    

    How it works:

    A lambda is created and executed when the get method is called. Then the error is caught and the exception thrown in your code is taken from it.

    P.S library for asserts - AssertJ



Suggested Topics

  • 3
  • 2
  • 2
  • 2
  • 2