Java Coding Nerd. This Blog will feature content-rich articles, tutorials and own opinions on variuos programming related topcis.


JUnit Rules: Using the JUnit TimeOut Rule

TimeOut Rule

TimeOut Rule

JUnit Rules

JUnit offers a set of Rules. A Rule is a specified behaviour for tests, which needs to be defined once and then can be used in more than just one place without writing redundant code. One of the is the TimeOut Rule.

What you need

  • A simple Maven
  • JUnit 4
  • Mockito

Add the JUnit 4 and JUnitParams dependency to your pom.xml

    <!-- -->

Futhermore we need a class called

Implementing the TimeOut Rule

Implenemting a Rule is quite easy

public Timeout globalTimeOut = new Timeout(50, TimeUnit.MILLISECONDS);

It is not just easy to implement but also  to understand. What we did is to make sure that every test in this class fails if does take longer than 50 milliseconds to complete.

We can test if this behaviour works with the following tests

public class TimeOutTest {
  public Timeout globalTimeOut = new Timeout(50, TimeUnit.MILLISECONDS);
  public void testShouldFailBecauseOfTimeOutRule() throws InterruptedException	{
  public void testShouldPassBecauseOfTimeOutRule() throws InterruptedException{


Of course this is not a test you should write. Actually you should not use threading in JUnit tests at all, but this example shows what you can do with a JUnit Rule.

There are other pre-defined Rules in JUnit you can have a look at them here


Spread the love

Leave a Reply

Theme by Anders Norén