Skip to content

Yet another programming solutions log

Sample bits from programming for the future generations.

Technologies Technologies
  • Algorithms and Data Structures
  • Java Tutorials
  • JUnit Tutorial
  • MongoDB Tutorial
  • Quartz Scheduler Tutorial
  • Spock Framework Tutorial
  • Spring Framework
  • Bash Tutorial
  • Clojure Tutorial
  • Design Patterns
  • Developer’s Tools
  • Productivity
  • About
Expand Search Form

JUnit exceptions, timeout and Ignore

farenda 2015-12-29 0

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!
Categories JUnit Tags java, junit, unit-tests
Previous: JUnit fixtures – code reuse
Next: JUnit Matchers CheatSheet

Recent Posts

  • Java 8 Date Time concepts
  • Maven dependency to local JAR
  • Caesar cipher in Java
  • Java casting trick
  • Java 8 flatMap practical example
  • Linked List – remove element
  • Linked List – insert element at position
  • Linked List add element at the end
  • Create Java Streams
  • Floyd Cycle detection in Java

Pages

  • About Farenda
  • Algorithms and Data Structures
  • Bash Tutorial
  • Bean Validation Tutorial
  • Clojure Tutorial
  • Design Patterns
  • Java 8 Streams and Lambda Expressions Tutorial
  • Java Basics Tutorial
  • Java Collections Tutorial
  • Java Concurrency Tutorial
  • Java IO Tutorial
  • Java Tutorials
  • Java Util Tutorial
  • Java XML Tutorial
  • JUnit Tutorial
  • MongoDB Tutorial
  • Quartz Scheduler Tutorial
  • Software Developer’s Tools
  • Spock Framework Tutorial
  • Spring Framework

Tags

algorithms bash bean-validation books clojure design-patterns embedmongo exercises git gof gradle groovy hateoas hsqldb i18n java java-basics java-collections java-concurrency java-io java-lang java-time java-util java-xml java8 java8-files junit linux lists log4j logging maven mongodb performance quartz refactoring regex rest slf4j solid spring spring-boot spring-core sql unit-tests

Yet another programming solutions log © 2021

sponsored