@MockBean Is Gone: Fixing Your Tests After Upgrading to Spring Boot 4
You bump the Spring Boot version to 4, run the build, and the main code compiles fine. Then the tests fail with a wall of errors like these: cannot find symbol symbol: class MockBean package org.springframework.boot.test.autoconfigure.web.servlet does not exist The test code itself is fine. Spring Boot 4 removed @MockBean and @SpyBean, split the test starter into one starter per technology, and…
When upgrading to Spring Boot 4, you may encounter issues with your existing tests. The main changes involve the removal of @MockBean and @SpyBean, the splitting of the test starter into separate starters for each technology, and the relocation of slice annotations to new packages. Here are the steps to address these changes:
1. Update test dependencies: In Spring Boot 4, each technology now has its own test starter. For example, to test a web controller, you'll need to add spring-boot-starter-webmvc-test and spring-boot-starter-data-jpa-test to your project's dependencies. These starters include JUnit, AssertJ, and Mockito, so you don't need to include spring-boot-starter-test alongside them.
2. Replace @MockBean with @MockitoBean: In Spring Boot 4, @MockBean has been moved to the Spring Framework (org.springframework.test.context.bean.override.mockito). To use it, simply change @MockBean to @MockitoBean on the field where you want to inject a mock object, and stub the mock using when(...) as before.
3. Adjust test imports: The WebMvcTest annotation has moved from org.springframework.boot.test.autoconfigure.web.servlet to org.springframework.boot.webmvc.test.autoconfigure. Replace imports from the old package with those from the new one. Additionally, you may need to change the test runner from @RunWith(MockMvc.class) to @ExtendWith(MockitoExtension.class) when using JUnit 5.
4. Update @SpyBean usage: When using @SpyBean, it's now necessary to use @MockitoSpyBean instead. This allows you to wrap the real bean and verify calls while still running real code. The rest of the test code remains the same.
5. Be aware of moved test annotations: @DataJpaTest and TestEntityManager have been moved to different packages in Spring Boot 4. Update your imports accordingly to ensure your tests compile without errors.
Rewritten by urgent.news; may contain errors — check the original.
Source: dev.to