Java Programming Tutorials

Java programming tutorials with many code examples!

JUnit exceptions, timeout and Ignore

Practical examples of JUnit handy features – expecting exceptions, limiting execution time, and exclusion from execution.

The @Test annotation has two more interesting features:

  • expecting exception to occur in test
    The test fails if an exception is not thrown.
  • waiting for tests to finish for specified time
    The test fails if it won’t finish in given time.

Both these features are straightforward to use as you can see in the following example. Especially useful is ability to test that an exception occurs.

package com.farenda.junit;

import org.junit.Ignore;
import org.junit.Test;

import java.util.Collections;
import java.util.concurrent.TimeUnit;

import static java.util.Collections.emptyList;
import static org.junit.Assert.assertEquals;

public class MoreFeaturesTest {

    @Ignore("Fix that tomorrow")
    @Test
    public void shouldBeFixedSoon() {
        assertEquals(4, Math.abs(-5));
    }

    @Test(timeout = 500)
    public void shouldDoWorkInSpecifiedTime() throws InterruptedException {
        TimeUnit.MILLISECONDS.sleep(1000);
        assertEquals(2, 2);
    }

    @Test(expected = IndexOutOfBoundsException.class)
    public void shouldThrowException() {
        Collections.swap(emptyList(), 0, 1);
    }
}

Another handy feature is @Ignore annotation that can be used to disable a test, as in the above example, or group of tests as in the example below:

package com.farenda.junit;

import org.junit.Ignore;
import org.junit.Test;

import static org.junit.Assert.assertEquals;

@Ignore("This is still work in progress")
public class WorkInProgressTest {

    @Test
    public void mathTest() {
        assertEquals(4, Math.abs(-5));
    }
}

How pros do it

Here’s an example of practical usage of JUnit’s @Ignore in Spring Framework:

package org.springframework.test.context.hierarchies.web;

import javax.servlet.ServletContext;

import org.junit.Ignore;
import org.junit.Test;

// ... truncated for brevity

import static org.junit.Assert.*;

/**
 * @author Sam Brannen
 * @since 3.2.2
 */
@ContextHierarchy(@ContextConfiguration)
public class DispatcherWacRootWacEarTests extends RootWacEarTests {

// ... truncated for brevity

        @Ignore("Superseded by verifyDispatcherWacConfig()")
        @Test
        @Override
        public void verifyEarConfig() {
                /* no-op */
        }

        @Ignore("Superseded by verifyDispatcherWacConfig()")
        @Test
        @Override
        public void verifyRootWacConfig() {
                /* no-op */
        }

        @Test
        public void verifyDispatcherWacConfig() {
                ApplicationContext parent = wac.getParent();
                assertNotNull(parent);
                assertTrue(parent instanceof WebApplicationContext);

                ApplicationContext grandParent = parent.getParent();
                assertNotNull(grandParent);
                assertFalse(grandParent instanceof WebApplicationContext);

                ServletContext dispatcherServletContext = wac.getServletContext();
                assertNotNull(dispatcherServletContext);
                ServletContext rootServletContext = ((WebApplicationContext) parent).getServletContext();
                assertNotNull(rootServletContext);
                assertSame(dispatcherServletContext, rootServletContext);

                assertSame(parent,
                        rootServletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE));
                assertSame(parent,
                        dispatcherServletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE));

                assertEquals("ear", ear);
                assertEquals("root", root);
                assertEquals("dispatcher", dispatcher);
        }

}

Another one from Spring Framework, but this time limiting execution time of a test:

package org.springframework.scheduling.config;

import org.junit.Test;

import org.springframework.context.support.GenericXmlApplicationContext;

/**
 * Tests ensuring that tasks scheduled using the <task:scheduled> element
 * are never marked lazy, even if the enclosing <beans> element declares
 * default-lazy-init="true". See  SPR-8498
 *
 * @author Mike Youngstrom
 * @author Chris Beams
 */
public class LazyScheduledTasksBeanDefinitionParserTests {

      @Test(timeout = 5000)
      public void checkTarget() {
              Task task =
                      new GenericXmlApplicationContext(
                                      LazyScheduledTasksBeanDefinitionParserTests.class,
                                      "lazyScheduledTasksContext.xml")
                              .getBean(Task.class);

              while (!task.executed) {
                      try {
                              Thread.sleep(10);
                      } catch (Exception e) { /* Do Nothing */ }
              }
      }

      static class Task {
              volatile boolean executed = false;

              public void doWork() {
                      executed = true;
              }
      }
}

The next example is from Hibernate ORM and illustrates how JUnit’s @Test(expected) can be used to verify that code is throwing exception as expected:

package org.hibernate.test.boot.cfgXml;

import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.engine.config.spi.ConfigurationService;
import org.hibernate.internal.util.config.ConfigurationException;

import org.hibernate.testing.junit4.BaseUnitTestCase;
import org.junit.Test;

import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.fail;

/**
 * @author Steve Ebersole
 */
public class CfgXmlParsingTest extends BaseUnitTestCase {

// ... other tests removed for brevity

      @Test(expected = ConfigurationException.class )
      public void testCfgXmlWithBadNamespaceAndSchemaLocation() {
              StandardServiceRegistry ssr = new StandardServiceRegistryBuilder()
                              .configure( "org/hibernate/test/boot/cfgXml/badnamespace.cfg.xml" )
                              .build();
              StandardServiceRegistryBuilder.destroy( ssr );
              fail( "Expecting the bad namespace to fail" );
      }
}
Share with the World!