1. Overview

Testing is critical for any application, whether a unit test or an integration test. SpringRunner and SpringBootTest classes form the foundation to run integration tests.

In this tutorial, we’ll learn about both. We’ll learn how to use them in our code and learn about their similarities and differences.

2. SpringRunner

SpringRunner is an alias for the class SpringJUnit4ClassRunner and works with JUnit4-based test classes. It loads Spring TestContext, through which spring beans and configurations become available to use along with JUnit annotations. We’ll require JUnit 4.12 or higher to use this.

To use this in code, annotate the test class with @RunWith(SpringRunner.class):

@RunWith(SpringRunner.class)
public class SampleIntegrationTest {

    @Test
    public void test() {
        //
    }
}

3. SpringBootTest

SpringBootTest is an alternative to SpringRunner and works with JUnit5. It’s also used to run integration tests and load Spring TestContext.

It is very rich and provides many configurations through its annotation arguments. It supports various web environment modes such as MOCK, RANDOM_PORT, DEFINED_PORT, and NONE. We can pass application properties through its annotation that is injected in the spring environment before the test runs:

@SpringBootTest(
  properties = {"user.name=test_user"},
  webEnvironment = MOCK)
public class SampleIntegrationTest {

    @Test
    public void test() {
        //
    }
}

The annotation @SpringBootTest is required at the class level to run the integration test.

4. Comparison Between SpringRunner and SpringBootTest

In this table, we’ll compare both the classes with their pros and cons.

SpringRunner

SpringBootTest

Use to run integration tests and load Spring TestContext

Use to run integration tests and load Spring TestContext

JUnit annotations are also available to use

JUnit annotations are also available to use

Needs JUnit4.12 or higher

Needs JUnit5 or higher

Not a rich API with respect to configuration

Offer a rich API to configure test configuration

Not recommended

Recommended as it supports new features and is simple to use

5. Conclusion

In this article, we learned about SpringRunner and SpringBootTest. We’ve learned how to use them. We’ve also compared them and learned their differences and similarities.

We should use SpringBootTest as it supports the latest JUnit, but whenever there is a requirement to use JUnit 4, SpringRunner is the option.