Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Spring Boot Web Test Slicing

DZone's Guide to

Spring Boot Web Test Slicing

Curious about Spring Boot's test slicing capabilities? Here's a run-through of how to use slice tests, which reduces boilerplate.

· Java Zone ·
Free Resource

Get the Edge with a Professional Java IDE. 30-day free trial.

Spring Boot introduced, if you'll recall, test slicing a while back, and it has taken me some time to get my head around it and explore some of its nuances.

Background

The main reason to use this feature is to reduce boilerplate. Consider a controller that looks like this, just for variety written using Kotlin.

@RestController
@RequestMapping("/users")
class UserController(
        private val userRepository: UserRepository,
        private val userResourceAssembler: UserResourceAssembler) {
 
    @GetMapping
    fun getUsers(pageable: Pageable, 
                 pagedResourcesAssembler: PagedResourcesAssembler<User>): PagedResources<Resource<User>> {
        val users = userRepository.findAll(pageable)
        return pagedResourcesAssembler.toResource(users, this.userResourceAssembler)
    }
 
    @GetMapping("/{id}")
    fun getUser(id: Long): Resource<User> {
        return Resource(userRepository.findOne(id))
    }
}


A traditional Spring Mock MVC test to test this controller would be along these lines:

@RunWith(SpringRunner::class)
@WebAppConfiguration
@ContextConfiguration
class UserControllerTests {
 
    lateinit var mockMvc: MockMvc
 
    @Autowired
    private val wac: WebApplicationContext? = null
 
    @Before
    fun setup() {
        this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build()
    }
 
    @Test
    fun testGetUsers() {
        this.mockMvc.perform(get("/users")
                .accept(MediaType.APPLICATION_JSON))
                .andDo(print())
                .andExpect(status().isOk)
    }
 
    @EnableSpringDataWebSupport
    @EnableWebMvc
    @Configuration
    class SpringConfig {
 
        @Bean
        fun userController(): UserController {
            return UserController(userRepository(), UserResourceAssembler())
        }
 
        @Bean
        fun userRepository(): UserRepository {
            val userRepository = Mockito.mock(UserRepository::class.java)
            given(userRepository.findAll(Matchers.any(Pageable::class.java)))
                    .willAnswer({ invocation ->
                        val pageable = invocation.arguments[0] as Pageable
                        PageImpl(
                                listOf(
                                        User(id = 1, fullName = "one", password = "one", email = "one@one.com"),
                                        User(id = 2, fullName = "two", password = "two", email = "two@two.com"))
                                , pageable, 10)
                    })
            return userRepository
        }
    }
}


There is a lot of ceremony involved in setting up such a test — a web application context that understands a web environment being pulled in, a configuration that sets up the Spring MVC environment needs to be created, and MockMvc, which handles the testing framework, needs to be set up before each test.

Web Slice Tests

A web slice test, when compared to the previous test, is far simpler and focuses on testing the controller and hiding a lot of the boilerplate code:
@RunWith(SpringRunner::class)
@WebMvcTest(UserController::class)
class UserControllerSliceTests {
 
    @Autowired
    lateinit var mockMvc: MockMvc
 
    @MockBean
    lateinit var userRepository: UserRepository
 
    @SpyBean
    lateinit var userResourceAssembler: UserResourceAssembler
 
    @Test
    fun testGetUsers() {
 
        this.mockMvc.perform(get("/users").param("page", "0").param("size", "1")
                .accept(MediaType.APPLICATION_JSON))
                .andDo(print())
                .andExpect(status().isOk)
    }
 
    @Before
    fun setUp(): Unit {
        given(userRepository.findAll(Matchers.any(Pageable::class.java)))
                .willAnswer({ invocation ->
                    val pageable = invocation.arguments[0] as Pageable
                    PageImpl(
                            listOf(
                                    User(id = 1, fullName = "one", password = "one", email = "one@one.com"),
                                    User(id = 2, fullName = "two", password = "two", email = "two@two.com"))
                            , pageable, 10)
                })
    }
}


It works by creating a Spring Application context but filtering out anything that is not relevant to the web layer and loading up only the controller, which has been passed into the @WebTest annotation. Any dependency that the controller requires can be injected in as a mock.

Coming to some of the nuances, say if I wanted to inject one of the fields myself, the way to do that is having the test use a custom Spring Configuration. For a test, this is done by using an inner static class annotated with @TestConfiguration the following way:
@RunWith(SpringRunner::class)
@WebMvcTest(UserController::class)
class UserControllerSliceTests {
 
    @Autowired
    lateinit var mockMvc: MockMvc
 
    @Autowired
    lateinit var userRepository: UserRepository
 
    @Autowired
    lateinit var userResourceAssembler: UserResourceAssembler
 
    @Test
    fun testGetUsers() {
 
        this.mockMvc.perform(get("/users").param("page", "0").param("size", "1")
                .accept(MediaType.APPLICATION_JSON))
                .andDo(print())
                .andExpect(status().isOk)
    }
 
    @Before
    fun setUp(): Unit {
        given(userRepository.findAll(Matchers.any(Pageable::class.java)))
                .willAnswer({ invocation ->
                    val pageable = invocation.arguments[0] as Pageable
                    PageImpl(
                            listOf(
                                    User(id = 1, fullName = "one", password = "one", email = "one@one.com"),
                                    User(id = 2, fullName = "two", password = "two", email = "two@two.com"))
                            , pageable, 10)
                })
    }
 
    @TestConfiguration
    class SpringConfig {
 
        @Bean
        fun userResourceAssembler(): UserResourceAssembler {
            return UserResourceAssembler()
        }
 
        @Bean
        fun userRepository(): UserRepository {
            return mock(UserRepository::class.java)
        }
    }
 
}


The beans from the "TestConfiguration" add onto the configuration that the Slice tests depend on and don't completely replace it.

On the other hand, if I wanted to override the loading of the main "@SpringBootApplication" annotated class, then I can pass in a Spring Configuration class explicitly, but the catch is that I have to now take care of loading up the relevant Spring Boot features myself (enabling auto-configuration, appropriate scanning, etc.), so a way around it is to explicitly annotate the configuration as a Spring Boot Application in the following way:

@RunWith(SpringRunner::class)
@WebMvcTest(UserController::class)
class UserControllerExplicitConfigTests {
 
    @Autowired
    lateinit var mockMvc: MockMvc
 
    @Autowired
    lateinit var userRepository: UserRepository
 
    @Test
    fun testGetUsers() {
 
        this.mockMvc.perform(get("/users").param("page", "0").param("size", "1")
                .accept(MediaType.APPLICATION_JSON))
                .andDo(print())
                .andExpect(status().isOk)
    }
 
    @Before
    fun setUp(): Unit {
        given(userRepository.findAll(Matchers.any(Pageable::class.java)))
                .willAnswer({ invocation ->
                    val pageable = invocation.arguments[0] as Pageable
                    PageImpl(
                            listOf(
                                    User(id = 1, fullName = "one", password = "one", email = "one@one.com"),
                                    User(id = 2, fullName = "two", password = "two", email = "two@two.com"))
                            , pageable, 10)
                })
    }
 
    @SpringBootApplication(scanBasePackageClasses = arrayOf(UserController::class))
    @EnableSpringDataWebSupport
    class SpringConfig {
 
        @Bean
        fun userResourceAssembler(): UserResourceAssembler {
            return UserResourceAssembler()
        }
 
        @Bean
        fun userRepository(): UserRepository {
            return mock(UserRepository::class.java)
        }
    }
 
}



The catch, though, is that now other tests may end up finding this inner configuration, which is far from ideal! So, my experience has been to depend on bare minimum slice testing and, if needed, extending it using @TestConfiguration.

I have a little more detailed code sample available at my Github repo, which has working examples to play with.

Get the Java IDE that understands code & makes developing enjoyable. Level up your code with IntelliJ IDEA. Download the free trial.

Topics:
java ,spring boot ,test slicing ,tutorial ,testing

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}