SpringBoot unit test example: basic unit testing

Now is the springboot world, so ,if you want to do unit test with spring boot, here is a tutorial, Let’s begin.

Since spring boot 1.5.9, spring has simplifed the unit test framework, it’s very easy to test springbeans now.

1. Pom.xml

Here we use spring boot 1.5.9

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

    </dependencies>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <!-- Import dependency management from Spring Boot -->
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-dependencies</artifactId>
                <version>1.5.9.RELEASE</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

2. Define on spring bean for test

Here we define a spring bean named DemoService for demo,which is a @Service bean contains a addCount method ,here is the code.

@Service("demo")
public class DemoService {
    public int addCount(int add1, int add2) {
        return add1+add2;
    }
}

Then we got this directory structure: The project directory structure screenshot

3. Now define the TestCase to test addCount method

Now it’s the trick:

@RunWith(SpringRunner.class) /* 1 */
@SpringBootTest				 /* 2 */
public class DemoServiceTests {
    @Autowired				 /* 3 */
    private DemoService demoService;

    @Test					/* 4 */
    public void testAddCount() {
        assertThat(demoService.addCount(1,1)).isEqualTo(2); /* 5 */
    }
}

the explain:

  1. @Runwith would tell the underground junit framework to run this test with spring runner
  2. @SpringBootTest would let this testcase setup the springboot env.
  3. @Autowired would inject the service bean we want to test
  4. @Test is the junit annotation
  5. assertThat is the assertJ static method to do assertions, it’s very concise and readable.

4. Now run the test

we got the result as follows: The testcase result screenshot

You can find detail documents about the springboot and unit testing here:

The example code can be found here: