Dec 30 2011

[JUnit-Rule] Fail tests on exceptions/failed assertions in other threads

I use JUnit a lot. But obviously it has its problems. Fortunately rules are a great way to solve a lot of those problems. At least one can work around them in most of the cases…

On speciallity that got me more than once:

JUnit ignores exceptions/assertions in other threads

JUnit tests only fail on exceptions that are thrown within the “main” thread. Exceptions (and also failed Assertions!) in all other Threads are simply ignored.

Simple test case:

  @Test
  public void ignoredAssertion() throws Exception {
    Thread thread = new Thread( new Runnable() {
      @Override
      public void run() {
        //Of course only one of the following lines is executed. Just comment one of those lines out...
        assertFalse(true); //will not be reported!
        throw new RuntimeException( "This one is ignored by JUnit, too" );
      }
    } );
    thread.start();
    thread.join();
  }

This test will be run successfully. (I don’t wanna discuss whether this behavior is correct or not. I know there are a lot of use cases where this is an important feature). And that is quite surprising for a lot of developers.

More important: It is very easy to miss some failed assertions if your code under test is multi threaded…

One rule to catch them all…

I have written a small rule that catches all exceptions on all threads and fails the test if at least one exception has been caught.

How to use the rule

Just add those lines to your test class:

  @Rule
  public CatchAllExceptionsRule catchAllExceptionsRule = new CatchAllExceptionsRule();

And it is guaranteed that your test fails on all (really all) uncaught exceptions.

The rule is deployed to Maven Central:

<dependency>
    <groupId>com.cedarsoft.commons</groupId>
    <artifactId>test-utils</artifactId>
    <version>5.0.9</version>
</dependency>

The rule itself:

/**
 * This rule catches exceptions on all threads and fails the test if such exceptions are caught
 *
 * @author Johannes Schneider (<a href="mailto:js@cedarsoft.com">js@cedarsoft.com</a>)
 */
public class CatchAllExceptionsRule implements TestRule {
  @Nullable
  private Thread.UncaughtExceptionHandler oldHandler;

  @Override
  public Statement apply( final Statement base, Description description ) {
    return new Statement() {
      @Override
      public void evaluate() throws Throwable {
        before();
        try {
          base.evaluate();
        } catch ( Throwable t ) {
          afterFailing();
          throw t;
        }

        afterSuccess();
      }
    };
  }

  private void before() {
    oldHandler = Thread.getDefaultUncaughtExceptionHandler();
    Thread.setDefaultUncaughtExceptionHandler( new Thread.UncaughtExceptionHandler() {
      @Override
      public void uncaughtException( Thread t, Throwable e ) {
        caught.add( e );
        if ( oldHandler != null ) {
          oldHandler.uncaughtException( t, e );
        }
      }
    } );
  }

  @Nonnull
  private final List<Throwable> caught = new ArrayList<Throwable>();

  private void afterSuccess() {
    Thread.setDefaultUncaughtExceptionHandler( oldHandler );

    if ( caught.isEmpty() ) {
      return;
    }

    throw new AssertionError( buildMessage() );
  }

  private String buildMessage() {
    StringBuilder builder = new StringBuilder();
    builder.append( caught.size() ).append( " exceptions thrown but not caught in other threads:\n" );

    for ( Throwable throwable : caught ) {
      builder.append( "---------------------\n" );

      StringWriter out = new StringWriter();
      throwable.printStackTrace( new PrintWriter( out ) );
      builder.append( out.toString() );
    }

    builder.append( "---------------------\n" );

    return builder.toString();
  }

  private void afterFailing() {
    Thread.setDefaultUncaughtExceptionHandler( oldHandler );
  }
}

You need some code to get this fixed.


Dec 9 2011

JUnit: Tired of those remaining Threads…

This happens more often that it should:

Unit tests run in isolation. But when you start the hole buch, some of the tests fail randomly.

Static initialization

This is the main reason for this behavior. Something is configured somewhere. And since static fields are involved, that (mis)configuration will have an impact on other tests. Very hard to discover. Good luck on that.

Remaining Threads

Another typical problem when running lots of unit tests are remaining threads.

When a unit test has finished, nobody checks for remaining threads. So those threads sill run, do some work, throw Exceptions that end up on the console, print debug statements, interrupt at break points during debugging…

Combined with some static initialization they guarantee for a lot of fun…

How to detect them?

I have written a short rule that detects whether some threads have been left after a unit test has finished. That rule stores all threads running at the beginning of the test. Then this set is compared with the set of all running tests at the end of the of a unit test.

While it does not detect all errors in all cases, it is very helpful to find some remaining ExecutorServices or BackgroundJobs. Just give it a try:

The rule can be used like all other rule (must be public):

  @Rule
  public ThreadRule threadRule = new ThreadRule();

If there are threads left after each test, an exception is thrown with the stack traces of each of the remaining threads:

java.lang.IllegalStateException: Some threads have been left:
// Remaining Threads:
-----------------------
---
Thread[Thread-0,5,main]
	at java.lang.Thread.sleep(Native Method)
	at com.cedarsoft.test.utils.ThreadRuleTest$2.run(ThreadRuleTest.java:34)
	at java.lang.Thread.run(Thread.java:662)
---
Thread[Thread-1,5,main]
	at java.lang.Thread.sleep(Native Method)
	at com.cedarsoft.test.utils.ThreadRuleTest$3.run(ThreadRuleTest.java:44)
	at java.lang.Thread.run(Thread.java:662)
-----------------------

	at com.cedarsoft.test.utils.ThreadRule.after(ThreadRule.java:67)
	at com.cedarsoft.test.utils.ThreadRule.access$200(ThreadRule.java:18)
	at com.cedarsoft.test.utils.ThreadRule$1.evaluate(ThreadRule.java:34)
	at org.junit.rules.RunRules.evaluate(RunRules.java:18)
	at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:263)
	at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:68)
	at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:47)
	at org.junit.runners.ParentRunner$3.run(ParentRunner.java:231)
	at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:60)
	at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:229)
	at org.junit.runners.ParentRunner.access$000(ParentRunner.java:50)
	at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:222)
	at org.junit.runners.ParentRunner.run(ParentRunner.java:300)
	at org.junit.runner.JUnitCore.run(JUnitCore.java:157)
[...]

The code

The rule is available as part of cedarsoft test-utils deployed to Maven Central. Just give it a try:

<dependency>
    <groupId>com.cedarsoft.commons</groupId>
    <artifactId>test-utils</artifactId>
    <version>5.0.8</version>
</dependency>

com.cedarsoft.test.utils.ThreadRule

For easy copy/pasta:

import com.google.common.base.Joiner;

import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

import javax.annotation.Nonnull;

import org.junit.rules.*;
import org.junit.runner.*;
import org.junit.runners.model.*;

public class ThreadRule implements TestRule {

  public static final String STACK_TRACE_ELEMENT_SEPARATOR = "\n\tat ";

  @Override
  public Statement apply( final Statement base, Description description ) {
    return new Statement() {
      @Override
      public void evaluate() throws Throwable {
        before();
        try {
          base.evaluate();
        } catch ( Throwable t ) {
          afterFailing();
          throw t;
        }
        after();
      }
    };
  }

  private Collection<Thread> initialThreads;

  private void before() {
    if ( initialThreads != null ) {
      throw new IllegalStateException( "???" );
    }

    initialThreads = Thread.getAllStackTraces().keySet();
  }

  @Nonnull
  public Collection<? extends Thread> getInitialThreads() {
    if ( initialThreads == null ) {
      throw new IllegalStateException( "not initialized yet" );
    }
    return Collections.unmodifiableCollection( initialThreads );
  }

  private void afterFailing() {
    Set<? extends Thread> remainingThreads = getRemainingThreads();
    if ( !remainingThreads.isEmpty() ) {
      System.err.print( "Some threads have been left:\n" + buildMessage( remainingThreads ) );
    }
  }

  private void after() {
    Set<? extends Thread> remainingThreads = getRemainingThreads();
    if ( !remainingThreads.isEmpty() ) {
      throw new IllegalStateException( "Some threads have been left:\n" + buildMessage( remainingThreads ) );
    }
  }

  @Nonnull
  private Set<? extends Thread> getRemainingThreads() {
    Collection<Thread> threadsNow = Thread.getAllStackTraces().keySet();

    Set<Thread> remainingThreads = new HashSet<Thread>( threadsNow );
    remainingThreads.removeAll( initialThreads );

    for ( Iterator<Thread> iterator = remainingThreads.iterator(); iterator.hasNext(); ) {
      Thread remainingThread = iterator.next();
      if ( !remainingThread.isAlive() ) {
        iterator.remove();
      }

      //Give the thread a very(!) short time to die off
      try {
        Thread.sleep( 10 );
      } catch ( InterruptedException ignore ) {
      }

      //Second try
      if ( !remainingThread.isAlive() ) {
        iterator.remove();
      }
    }
    return remainingThreads;
  }

  @Nonnull
  private String buildMessage( @Nonnull Set<? extends Thread> remainingThreads ) {
    StringBuilder builder = new StringBuilder();

    builder.append( "// Remaining Threads:" ).append( "\n" );
    builder.append( "-----------------------" ).append( "\n" );
    for ( Thread remainingThread : remainingThreads ) {
      builder.append( "---" );
      builder.append( "\n" );
      builder.append( remainingThread );
      builder.append( STACK_TRACE_ELEMENT_SEPARATOR );
      builder.append( Joiner.on( STACK_TRACE_ELEMENT_SEPARATOR ).join( remainingThread.getStackTrace() ) );
      builder.append( "\n" );
    }
    builder.append( "-----------------------" ).append( "\n" );

    return builder.toString();
  }
}

Aug 25 2010

[Unit Testing]: Time zone and stuff…

Do you know those nasty time zone related bugs, too?
They are quite common – but often they are discovered when it is too late. Often every developer and tester lives in the same time zone. So sometimes the software is never ever run in a different time zone until it is shipped…

The problem

The idea of time zones makes calculating with dates/times really difficult.
But probably we have to live with them for a few more years…

So as developers we have to handle them properly.

And handling them properly means two things

Using a nice API

I am certain that it is impossible to write bug free code using just the standard Calendar stuff.
Maybe James Gosling is able to do that – but I even doubt that…

So just use one of those APIs that work. My personal favorite is Joda Time. Many cases then just work.

Testing time zones

As soon as your software handles dates/times it is necessary to test that code.
But my experience shows that hardly anybody tests anything that needs a lot of work to test. And changing the time zone manually needs some (too much?) work.

The solution

JUnit offers rules. Very simple but powerful feature. I have created several custom rules that make live much easier…

And I have created a timezone rule (based on Joda Time) that allows me to run my unit tests in different time zones.
Here it comes:

import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.joda.time.DateTimeZone;
import org.junit.rules.*;
import org.junit.runners.model.*;

/**
* Rule that sets the TimeZone
*
* @author Johannes Schneider (js@cedarsoft.com)
*/
public class DateTimeZoneRule implements MethodRule {
@NotNull
protected final DateTimeZone zone;

public DateTimeZoneRule() throws IllegalArgumentException {
this( "America/New_York" );
}

public DateTimeZoneRule( @NotNull @NonNls String zoneId ) throws IllegalArgumentException {
this( DateTimeZone.forID( zoneId ) );
}

public DateTimeZoneRule( @NotNull DateTimeZone zone ) {
this.zone = zone;
}

private DateTimeZone oldTimeZone;

@Override
public Statement apply( final Statement base, FrameworkMethod method, Object target ) {
return new Statement() {
@Override
public void evaluate() throws Throwable {
before();
try {
base.evaluate();
} finally {
after();
}
}
};
}

private void before() {
oldTimeZone = DateTimeZone.getDefault();
DateTimeZone.setDefault( zone );
}

private void after() {
DateTimeZone.setDefault( oldTimeZone );
}

@NotNull
public DateTimeZone getZone() {
return zone;
}

@NotNull
public DateTimeZone getOldTimeZone() {
if ( oldTimeZone == null ) {
throw new IllegalStateException( "No old zone set" );
}
return oldTimeZone;
}
}

No magic, nothing special, no rocket science.

Just start using rules – if will change the world into a better place…


Aug 24 2010

JUnit: Rules

JUnit has a nice feature now: Rules.
While I don’t like every detail of the implementation, they are basically a very good thing.

This is a short introduction how to use them…

What are rules

Rules are basically wrappers around test methods. They offer a nice way to prepare before a test run and clean up afterwards.
Basically they replace that awful setup/tearDown method stuff…

How to use them

Just create a public (non-static) field for the rule. And add the annotation @Rule.

Example

One of my favorite rules is TemporaryFolder. That rule creates a temporary folder and an easy way to create files and folders…

public class RulesTest {
@Rule
public TemporaryFolder tmp = new TemporaryFolder();

@Test
public void testIt() throws IOException {
  System.out.println( "Creating tmp folder @ " + tmp.newFolder( "aFolder" ).getAbsolutePath() );
  assertTrue( tmp.newFile( "a file" ).exists() );
}
}

The output of this test is (at least on my system):

Creating tmp folder @ /tmp/junit8120700871928645940/aFolder

What to do now?

1. Create a template for your IDE that adds the rule field…

It really is worth it. Please. I know the human being tries to avoid the initial setup costs (of maybe 3 minutes) and prefers to type the same lines several hundred times…

2. Enjoy writing Unit tests (again)

No more long and ugly setup/tearDown methods. No more files accidentally left in the tmp folder…

In the next posts I will show you some more rules that I find very useful….


Jul 10 2010

JUnit @Theory oddities

At the moment I try to switch my tests for serialization.cedarsoft.org over to JUnit Theories (4.8.1).

And I run into some problems:

No DataPoints

@RunWith( Theories.class )
public class TheoriesTest {
@Theory
public void aTheory( String arg ) {
System.out.println( "TheoriesTest.aTheory(" + arg + ")" );
assertNotNull( arg );
}
}

Throws an exception: java.lang.AssertionError: Never found parameters that satisfied method assumptions. Violated assumptions: []

Very nice. A theory doesn’t make any sense without any DataPoints.

A DataPoint method

Okay, now I created a DataPoints method:

@DataPoint
public static String getParam() {
return "daParam";
}

And everything works as expected.

Removing the static keyword

In my test cases I try to avoid every unnecessary key press as good as I can. Therefore I would like to create an abstract method that I just have to implement (IDE creates the method stub for me then).

So I just removed the static keyword from the method to try if it is possible…

And guess what?

The test method did not run – but is reported as succeeded…