Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Library for Asserting Multi Thread Code in Java

As a TDD practitioner I want to test everything I code.

During the last couple of years I've been coding many multithreaded code and one part of my tests have been bothering very much.

When I have to assert something that may happen during the run() loop i end up with some kind o assertion like this:

assertEventually(timeout, assertion)

I know that Mockito has a solution for this, but only for the verify call. I know also that JUnit has a timeout property that is useful to avoid hanging (or ever lasting) tests. But what I want is something that allows me to assert something that may become true over time.

So my question is, does anyone knows a library that provides this?

Here is my solution so far:

private void assertEventually(int timeoutInMilliseconds, Runnable assertion){
    long begin = System.currentTimeMillis();
    long now = begin;
    Throwable lastException = null;
    do{
        try{
            assertion.run();
            return;
        }catch(RuntimeException e){
            lastException = e;
        }catch(AssertionError e){
            lastException = e;
        }
        now = System.currentTimeMillis(); 
    }while((now - begin) < timeoutInMilliseconds);
    throw new RuntimeException(lastException);
}

Using it ends up like this:

assertEvetuallyTrue(1000, new Runnable() {
        public void run() {
            assertThat(Thread.activeCount()).isEqualTo(before);
        }
    });
like image 428
Fabricio Buzeto Avatar asked Aug 14 '13 19:08

Fabricio Buzeto


People also ask

Is there multi threading in Java?

Java supports multithreading through Thread class. Java Thread allows us to create a lightweight process that executes some tasks. We can create multiple threads in our program and start them.

Is junit multithreaded?

4.1 concurrent-junitConcurrent-junit library helps the users to test the methods for multi threading. It will create threads for testing methods. By default, number of threads created by this library is 4, but we can set the desired number of threads.


1 Answers

Two libraries you may want to check out:

  • ConcurrentUnit - allows you to perform assertions from any thread, waiting a fixed amount of time
  • Awaitility - allows you to wait a fixed amount of time or until some condition is satisfied
like image 155
Jonathan Avatar answered Oct 12 '22 09:10

Jonathan