Breaking News: Grepper is joining You.com. Read the official announcement!
Check it out

Testing web controllers with MockMVC

Pragya Keshap answered on February 15, 2023 Popularity 3/10 Helpfulness 1/10

Contents


More Related Answers

  • Mock MVC Test with Spring Boot
  • MockMvc Test Setup
  • Invoke and Test an API Endpoint with MockMvc
  • How to Test Spring MVC Controllers?
  • What is MockMvc?
  • What is the use of WebMvcTest annotation in Spring MVC applications?
  • springboottest vs mockmvc test
  • How to test async rest controller with MockMvc
  • Unit Testing With @WebMvcTest
  • To test the Controllers, we can use @WebMvcTest
  • Spring WebFlux how to test controllers using webTestClient
  • Testing the Web Layer With @WebMvcTest
  • How do you write a unit test with MockMVC?
  • @WebMvcTest:

  • Testing web controllers with MockMVC

    0

    This tiny test class can be explained as follows:

    @WebMvcTest: A Spring Boot test annotation that enables Spring MVC’s machinery. The controllers parameter constrains this test suite to only the HomeController class.

    @Autowired MockMvc mvc: @WebMvcTest adds an instance of Spring’s MockMvc utility to the application context. Then, we can autowire it into our test suite for all test methods to use.

    @MockBean VideoService videoService: This bean is a required component of HomeController. Using Spring Boot Test’s @MockBean annotation creates a mocked version of the bean and adds it into the application context.

    @Test: Denotes this method as a JUnit 5 test case.

    @WithMockUser: This annotation from Spring Security Test simulates a user logging in with a username of user and an authority of ROLE_USER (default values).

    The first line uses MockMvc to perform a get("/").

    The subsequent clauses perform a series of assertions, including verifying whether the result is an HTTP 200 (OK) response code and that the content contains a username of user and an authority of ROLE_USER. Then, it wraps up the MockMVC call by grabbing the entire response as a string.

    Following the MockMVC call is an AssertJ assertion, verifying bits of HTML output.

    Popularity 3/10 Helpfulness 1/10 Language java
    Source: Grepper
    Link to this answer
    Share Copy Link
    Contributed on Feb 15 2023
    Pragya Keshap
    0 Answers  Avg Quality 2/10


    X

    Continue with Google

    By continuing, I agree that I have read and agree to Greppers's Terms of Service and Privacy Policy.
    X
    Grepper Account Login Required

    Oops, You will need to install Grepper and log-in to perform this action.