0
0
JUnittesting~5 mins

@WebMvcTest for controller testing in JUnit - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is the purpose of the @WebMvcTest annotation in Spring Boot testing?

@WebMvcTest is used to test Spring MVC controllers specifically. It loads only the web layer components, making tests faster and focused on controller behavior without starting the full application context.

Click to reveal answer
intermediate
Which Spring components are loaded by default when using @WebMvcTest?

Only the web layer components like controllers, @ControllerAdvice, Jackson converters, and related MVC components are loaded. Services, repositories, and other beans are not loaded unless explicitly mocked.

Click to reveal answer
intermediate
How do you mock a service dependency in a @WebMvcTest controller test?

You use @MockBean to create a mock of the service and inject it into the controller. This way, the controller can call the mock service during the test.

Click to reveal answer
beginner
What is the role of MockMvc in @WebMvcTest?

MockMvc allows you to perform HTTP requests to the controller endpoints in tests without starting a server. It simulates web requests and verifies responses.

Click to reveal answer
beginner
Why is @WebMvcTest preferred over @SpringBootTest for controller testing?

@WebMvcTest loads only the web layer, making tests faster and more focused. @SpringBootTest loads the full application context, which is slower and not necessary for controller unit tests.

Click to reveal answer
What does @WebMvcTest load by default?
AOnly Spring MVC controllers and related web components
BThe full Spring application context
COnly service and repository beans
DNo beans, only configuration
How do you provide a mock service to a controller in a @WebMvcTest?
AUsing <code>@Autowired</code>
BUsing <code>@MockBean</code>
CUsing <code>@Service</code>
DUsing <code>@Component</code>
Which class is used to simulate HTTP requests in @WebMvcTest?
ARestTemplate
BTestRestTemplate
CMockMvc
DWebClient
Why might @WebMvcTest tests run faster than @SpringBootTest tests?
ABecause it loads only the web layer, not the full application context
BBecause it runs tests in parallel automatically
CBecause it uses a real database
DBecause it disables logging
If a controller depends on a service, but you forget to mock the service in a @WebMvcTest, what will happen?
AThe controller will ignore the service
BThe test will pass without errors
CThe service will be automatically created
DThe test will fail with a <code>NoSuchBeanDefinitionException</code>
Explain how @WebMvcTest helps in testing Spring MVC controllers and how you handle dependencies like services.
Think about isolating the controller from other layers.
You got /4 concepts.
    Describe the difference between @WebMvcTest and @SpringBootTest when testing a Spring Boot application.
    Consider scope and speed of tests.
    You got /4 concepts.