JavaCodingNerd

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

Testing

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

<dependencies>
    <!-- https://mvnrepository.com/artifact/junit/junit -->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
      <scope>test</scope>
    </dependency>
 
  </dependencies>

Futhermore we need a class called TimeOutTest.java

Implementing the TimeOut Rule

Implenemting a Rule is quite easy

@Rule
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 {
  
  @Rule
  public Timeout globalTimeOut = new Timeout(50, TimeUnit.MILLISECONDS);
  
  
  @Test
  public void testShouldFailBecauseOfTimeOutRule() throws InterruptedException	{
    
    Thread.sleep(51);
  }
  
  @Test
  public void testShouldPassBecauseOfTimeOutRule() throws InterruptedException{
    
    Thread.sleep(49);
  }
  
  
  

}

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

Rules

Spread the love

Leave a Reply

Theme by Anders Norén