Skip to content

How to use spring boot test to test controller and services

1. Overview

Unit Testing is very import in program,In this tutorial, I will writing tests using the framework in Spring Boot. I’ll cover unit tests that can run in isolation as well as integration tests that will bootstrap Spring context before executing tests by spring-boot-starter-web.

2. Project Set Up

The application we're going to use in this example is a restful api on user resource. include controller, service and mapper.

project

3. Maven Dependencies

xml
     <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.5.7</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
        </dependency>
    </dependencies>

4. Code

controller

java
@RestController
@Slf4j
@RequestMapping("user")
public class TestController {

    @Value("${env.name}")
    private String env;
    private final TUserService userService;

    public TestController(TUserService userService) {
        this.userService = userService;
    }

    @GetMapping("{id}")
    private TUser getById(@PathVariable String id) {
        log.info("current env {}",env);
        return userService.getById(id);
    }
}

service

java
public interface TUserService extends IService<TUser> {

}
java
@Service
public class TUserServiceImpl extends ServiceImpl<TUserMapper, TUser>
    implements TUserService{

}

Mapper

java
public interface TUserMapper extends BaseMapper<TUser> {

}

domain

java
@TableName(value = "t_user")
@Data
public class TUser {

    private Long id;

    @TableField(value = "t_username")
    private String username;

    @TableField(value = "t_password")
    private String password;

    @TableField(value = "t_phone")
    private String phone;

    @TableField(value = "t_address")
    private String address;
}

5. Test

  • base class
java
@SpringBootTest
@ActiveProfiles(value = "test")
public class TestApplication {
}

ControllerTest

java
@AutoConfigureMockMvc
public class UserControllerTest extends TestApplication {

    @Autowired
    private MockMvc mockMvc;
    @Test
    public void testGetUserById() throws Exception {
        MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.get("/user/1");
        MvcResult mvcResult = mockMvc.perform(builder)
                .andExpect(MockMvcResultMatchers.status().isOk())
                .andExpect(MockMvcResultMatchers.jsonPath("$.id").value(1))
                .andReturn();
    }
}

ServiceTest

java
public class UserServiceTest extends TestApplication {

    @Autowired
    private TUserService userService;

    @Test
    public void test() {
        TUser user = userService.getById(1);
        Assertions.assertEquals(user.getUsername(),"lcd");
    }
}

6. Conclusion

In this article, we took a deep dive into the testing support in Spring Boot and showed how to write unit tests efficiently.

Released under the MIT License.