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);
}
});
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.
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.
Two libraries you may want to check out:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With