Bird
Raised Fist0
Spring Bootframework~20 mins

@WebMvcTest for controller testing in Spring Boot - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
WebMvcTest Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
What does @WebMvcTest load in the Spring context?
When you use @WebMvcTest on a controller class, which parts of the Spring application context are loaded for the test?
ANo Spring context is loaded; it runs the controller in isolation without Spring support.
BOnly the web layer components like controllers, filters, and related MVC components are loaded.
COnly the repository layer is loaded to test database interactions.
DThe entire application context including services, repositories, and controllers is loaded.
Attempts:
2 left
💡 Hint
Think about what is needed to test just the web layer without starting the full app.
❓ state_output
intermediate
2:00remaining
What is the HTTP status returned by this @WebMvcTest controller test?
Given this controller and test, what HTTP status code will the test receive?
Spring Boot
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.junit.jupiter.api.Test;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

@WebMvcTest(HelloController.class)
class HelloControllerTest {
    @Autowired
    private MockMvc mockMvc;

    @Test
    void testHello() throws Exception {
        mockMvc.perform(get("/hello"))
               .andExpect(status().isOk());
    }
}

@RestController
class HelloController {
    @GetMapping("/hello")
    public String sayHello() {
        return "Hello!";
    }
}
A404 Not Found
B500 Internal Server Error
C200 OK
D302 Found (Redirect)
Attempts:
2 left
💡 Hint
The controller has a GET mapping for /hello that returns a string.
📝 Syntax
advanced
2:00remaining
Which @WebMvcTest annotation usage is correct for testing multiple controllers?
You want to test two controllers, UserController and OrderController, using @WebMvcTest. Which annotation usage is correct?
A@WebMvcTest({UserController.class, OrderController.class})
B@WebMvcTest(UserController.class, OrderController.class)
C@WebMvcTest(controllers = UserController.class, OrderController.class)
D@WebMvcTest(controllers = {UserController.class, OrderController.class})
Attempts:
2 left
💡 Hint
Check the syntax for specifying multiple controllers in the annotation attribute.
🔧 Debug
advanced
2:00remaining
Why does this @WebMvcTest fail with NoSuchBeanDefinitionException?
This test fails with NoSuchBeanDefinitionException for UserService. Why?
Spring Boot
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.junit.jupiter.api.Test;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

@WebMvcTest(UserController.class)
class UserControllerTest {
    @Autowired
    private MockMvc mockMvc;

    @Test
    void testUser() throws Exception {
        mockMvc.perform(get("/user"))
               .andExpect(status().isOk());
    }
}

@RestController
class UserController {
    private final UserService userService;

    public UserController(UserService userService) {
        this.userService = userService;
    }

    @GetMapping("/user")
    public String getUser() {
        return userService.getName();
    }
}

interface UserService {
    String getName();
}
AThe UserService bean is not found because @WebMvcTest does not load service beans unless mocked.
BUserService is an interface and cannot be mocked with @MockBean.
CThe test forgot to add @MockBean for UserService, so Spring cannot inject it.
DThe controller constructor is missing @Autowired, so injection fails.
Attempts:
2 left
💡 Hint
Think about what beans @WebMvcTest loads and how to provide dependencies.
🧠 Conceptual
expert
3:00remaining
What is the main advantage of using @WebMvcTest over @SpringBootTest for controller tests?
Why would a developer choose @WebMvcTest instead of @SpringBootTest when testing controllers?
A@WebMvcTest loads only the web layer, making tests faster and more focused on controller logic.
B@WebMvcTest automatically mocks all dependencies, so no manual mocking is needed.
C@WebMvcTest runs the full application context including database connections for integration testing.
D@WebMvcTest disables Spring Security, so tests do not require authentication setup.
Attempts:
2 left
💡 Hint
Consider test speed and scope of loaded beans.

Practice

(1/5)
1. What is the main purpose of using @WebMvcTest in Spring Boot testing?
easy
A. To test only the web layer (controllers) without starting the full application context
B. To test the entire Spring Boot application including database and services
C. To perform integration testing with real HTTP calls
D. To test only the service layer without controllers

Solution

  1. Step 1: Understand the role of @WebMvcTest

    @WebMvcTest is designed to load only the Spring MVC components like controllers, filters, and related configurations, not the full app context.
  2. Step 2: Compare with other test annotations

    Unlike @SpringBootTest which loads the full context, @WebMvcTest focuses on controller layer for fast, isolated web tests.
  3. Final Answer:

    To test only the web layer (controllers) without starting the full application context -> Option A
  4. Quick Check:

    @WebMvcTest = controller-only test [OK]
Hint: Remember @WebMvcTest loads only controllers, not full app [OK]
Common Mistakes:
  • Thinking @WebMvcTest loads full Spring context
  • Confusing @WebMvcTest with @SpringBootTest
  • Assuming it tests service or repository layers
2. Which of the following is the correct way to declare a test class using @WebMvcTest for a controller named UserController?
easy
A. @WebMvcTest(UserController.class) public class UserControllerTest {}
B. @WebMvcTest public class UserControllerTest {}
C. @WebMvcTest(services = UserController.class) public class UserControllerTest {}
D. @WebMvcTest(controllers = UserController.class) public class UserControllerTest {}

Solution

  1. Step 1: Check @WebMvcTest syntax for specifying controllers

    The correct syntax to specify which controllers to test is using the 'controllers' attribute, e.g., @WebMvcTest(controllers = UserController.class).
  2. Step 2: Eliminate incorrect options

    @WebMvcTest(UserController.class) public class UserControllerTest {} misses 'controllers =' keyword, @WebMvcTest public class UserControllerTest {} does not specify controller, @WebMvcTest(services = UserController.class) public class UserControllerTest {} wrongly uses 'services' attribute.
  3. Final Answer:

    @WebMvcTest(controllers = UserController.class) public class UserControllerTest {} -> Option D
  4. Quick Check:

    @WebMvcTest(controllers = ...) is correct syntax [OK]
Hint: Use 'controllers =' to specify controller class in @WebMvcTest [OK]
Common Mistakes:
  • Omitting 'controllers =' keyword
  • Using 'services =' instead of 'controllers ='
  • Not specifying any controller class
3. Given the following test code snippet using @WebMvcTest and MockMvc, what will be the HTTP status returned by the test?
@WebMvcTest(controllers = HelloController.class)
public class HelloControllerTest {

  @Autowired
  private MockMvc mockMvc;

  @Test
  public void testHello() throws Exception {
    mockMvc.perform(get("/hello"))
           .andExpect(status().isOk());
  }
}

@RestController
class HelloController {
  @GetMapping("/hello")
  public String sayHello() {
    return "Hello World";
  }
}
medium
A. 404 Not Found
B. 200 OK
C. 500 Internal Server Error
D. 302 Found (Redirect)

Solution

  1. Step 1: Analyze the controller mapping

    The HelloController has a GET mapping for '/hello' that returns a string "Hello World".
  2. Step 2: Understand MockMvc test behavior

    The test performs a GET request to '/hello' and expects status 200 OK, which matches the controller's response.
  3. Final Answer:

    200 OK -> Option B
  4. Quick Check:

    GET /hello returns 200 OK [OK]
Hint: Check controller mappings match test request URL [OK]
Common Mistakes:
  • Expecting 404 when mapping exists
  • Confusing status codes for successful GET
  • Missing controller in @WebMvcTest causing 404
4. Identify the error in the following @WebMvcTest test class that causes the test to fail with a NullPointerException.
@WebMvcTest(controllers = UserController.class)
public class UserControllerTest {

  private MockMvc mockMvc;

  @Test
  public void testGetUser() throws Exception {
    mockMvc.perform(get("/user/1"))
           .andExpect(status().isOk());
  }
}
medium
A. Missing @Autowired annotation on MockMvc field
B. Wrong controller class specified in @WebMvcTest
C. Missing @Test annotation on test method
D. MockMvc cannot perform GET requests

Solution

  1. Step 1: Check MockMvc initialization

    The MockMvc field is declared but not initialized or injected, so it remains null causing NullPointerException.
  2. Step 2: Fix by adding @Autowired

    Adding @Autowired on the MockMvc field lets Spring inject the mockMvc instance for testing.
  3. Final Answer:

    Missing @Autowired annotation on MockMvc field -> Option A
  4. Quick Check:

    MockMvc must be @Autowired to avoid null [OK]
Hint: Always @Autowired MockMvc in @WebMvcTest classes [OK]
Common Mistakes:
  • Forgetting @Autowired on MockMvc
  • Assuming MockMvc is auto-initialized without annotation
  • Misnaming test methods without @Test
5. You want to test a controller OrderController that depends on a service OrderService. Using @WebMvcTest, how can you provide a mock OrderService to the controller during testing?
hard
A. Create a new OrderService instance manually in the test method
B. Use @Autowired on OrderService field to inject real service
C. Use @MockBean on OrderService field in the test class to inject a mock
D. Use @SpringBootTest instead of @WebMvcTest to load full context

Solution

  1. Step 1: Understand @WebMvcTest scope

    @WebMvcTest loads only web layer, so service beans are not loaded automatically.
  2. Step 2: Use @MockBean to provide mock dependencies

    Annotating OrderService with @MockBean in the test class creates and injects a mock into the controller.
  3. Final Answer:

    Use @MockBean on OrderService field in the test class to inject a mock -> Option C
  4. Quick Check:

    @MockBean mocks service dependencies in @WebMvcTest [OK]
Hint: Use @MockBean to mock services in @WebMvcTest [OK]
Common Mistakes:
  • Trying to @Autowired real service in @WebMvcTest
  • Not mocking service causing NoSuchBeanDefinitionException
  • Switching to @SpringBootTest unnecessarily
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard