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 Assume – execute tests conditionally

farenda 2016-01-06 0

JUnit Assume is a handy feature that allows developer to specify assumptions about execution environment and hence execute tests conditionally. It’s practical and easy to use.

Sometimes it happens that you have to write a test that works only on a specific operating system (e.g. Linux) or in some environment you don’t control (e.g. Continuous Integration server). This way or another you would like to execute/disable it when some conditions are met. JUnit Assumptions is the feature that serves exactly that purpose.

To state conditions for your tests you need to use static methods from org.junit.Assume class as in the following example. When JUnit’s test runner will run a test it will execute assumption (e.g. assumeThat method) and will execute the rest of the test when the assumption is met, else it will ignore the test!

org.junit.Assume class provides only a handful of methods, because it’s meant to be used with CoreMatchers – see the post about JUnit Matchers if you need a refresher!

package com.farenda.junit;

import org.junit.Test;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;

import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.junit.Assume.*;

public class AssumptionsTest {

    @Test
    public void shouldRunOnlyOnLinux() {
        assumeThat(System.getProperty("os.name"), is("Linux"));
        assertThat(Paths.get("/tmp").toString(), equalTo("/tmp"));
    }

    @Test
    public void shouldRunOnlyWhenOneIsOne() {
        assumeTrue("Expected true!", 1 == 1);
        assertThat(1 + 1, is(2));
    }

    @Test
    public void shouldRunOnlyWhenFalse() {
        assumeFalse("Expected false!", 1 == 2);
        assertThat(Math.pow(2, 3), is(8.0));
    }

    @Test
    public void shouldRunOnlyWhenCanOpenFile() {
        List<String> data = null;
        try {
            data = Files.readAllLines(Paths.get("/proc/meminfo"));
        } catch (IOException e) {
            assumeNoException(e);
        }
        assertThat(data.isEmpty(), is(false));
    }
}

Cool thing is that assumptions can be specified on fixtures too, so you can put them in @Before/@After and @BeforeClass/@AfterClass methods to include/exclude all the tests! Nice. :-)

How pros do it

Let’s see an example from Spring Framework – Log4jWebConfigurerTests:

package org.springframework.web.util;

import org.junit.Test;

import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
import static org.junit.Assume.*;

// other imports cut for brevity

/**
 * @author Juergen Hoeller
 * @author Sam Brannen
 * @since 21.02.2005
 */
@SuppressWarnings("deprecation")
public class Log4jWebConfigurerTests {

    // ... other tests cut for brevity

    @Test
    public void initLoggingWithAbsoluteFilePathAndRefreshInterval() {
        // Only works on MS Windows
        assumeThat(System.getProperty("os.name"), containsString("Windows"));
        URL url = Log4jWebConfigurerTests.class.getResource(TESTLOG4J_PROPERTIES);
        initLogging(url.getFile(), true);
    }
}

In the next example, this time ServiceBootstrappingTest from Hibernate ORM, we can see that a test is executed only if SHOW_SQL property hasn’t been passed:

package org.hibernate.test.service;

// imports cut for brevity

import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;

import java.util.Properties;

import org.junit.Assume;
import org.junit.Test;

/**
 * @author Steve Ebersole
 */
@RequiresDialect( H2Dialect.class )
public class ServiceBootstrappingTest extends BaseUnitTestCase {
    @Test
    public void testBasicBuild() {
        // this test requires that SHOW_SQL property isn't passed from the outside (eg. via Gradle)
        final String showSqlPropertyFromOutside = System.getProperty(Environment.SHOW_SQL);
        Assume.assumeFalse("true".equals(showSqlPropertyFromOutside));

        final StandardServiceRegistryImpl serviceRegistry = (StandardServiceRegistryImpl) new StandardServiceRegistryBuilder()
                .applySettings( ConnectionProviderBuilder.getConnectionProviderProperties() )
                .build();
        final JdbcServices jdbcServices = serviceRegistry.getService( JdbcServices.class );

        assertTrue( jdbcServices.getDialect() instanceof H2Dialect );

        final ConnectionProviderJdbcConnectionAccess connectionAccess = assertTyping(
                ConnectionProviderJdbcConnectionAccess.class,
                jdbcServices.getBootstrapJdbcConnectionAccess()
        );
        assertTrue( connectionAccess.getConnectionProvider().isUnwrappableAs( DriverManagerConnectionProviderImpl.class ) );
        assertFalse( jdbcServices.getSqlStatementLogger().isLogToStdout() );

        serviceRegistry.destroy();
    }

    // other tests cut for brevity
}

We live in beautiful times when we can learn a lot from masters! Thanks! :-)

Share with the World!
Categories JUnit Tags java, junit, unit-tests
Previous: JUnit Parameterized tests
Next: JUnit test execution order

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 © 2022

sponsored