DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Spring Boot: User Login API Test Client Using Rest Assured
  • Spring Boot Delete User Details API Test Client Using Rest Assured | API Testing Using Rest Assured
  • Spring Boot Pet Clinic App: A Performance Study
  • Spring Boot: Test Restful Web Service Using Curl Client

Trending

  • Understanding IEEE 802.11(Wi-Fi) Encryption and Authentication: Write Your Own Custom Packet Sniffer
  • Accelerating AI Inference With TensorRT
  • Mastering Advanced Aggregations in Spark SQL
  • Enhancing Security With ZTNA in Hybrid and Multi-Cloud Deployments
  1. DZone
  2. Coding
  3. Frameworks
  4. Spring Boot Web Test Slicing

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.

By 
Biju Kunjummen user avatar
Biju Kunjummen
·
Jul. 05, 17 · Tutorial
Likes (6)
Comment
Save
Tweet
Share
26.3K Views

Join the DZone community and get the full member experience.

Join For Free

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.

Spring Framework Spring Boot Testing Web application

Published at DZone with permission of Biju Kunjummen, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Spring Boot: User Login API Test Client Using Rest Assured
  • Spring Boot Delete User Details API Test Client Using Rest Assured | API Testing Using Rest Assured
  • Spring Boot Pet Clinic App: A Performance Study
  • Spring Boot: Test Restful Web Service Using Curl Client

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!