To replace a bean in the runtime configuration of SpringBootTest, you can use the @MockBean annotation.
Let's say you want to replace the UserService bean with a mock implementation in your test.
First, create a mock implementation of the UserService interface using a mocking framework such as Mockito:
@Mock
private UserService userServiceMock;
Then you can use the @MockBean annotation to replace the UserService bean with the mock implementation:
@SpringBootTest
public class MyTest {
@Autowired
private UserService userService;
@MockBean
private UserService userServiceMock;
// ...
}
Now when the test runs, Spring will inject the mock implementation of UserService instead of the real one. You can then define behavior for the mock implementation to simulate different scenarios and test your application logic accordingly.
Asked: 2023-07-20 12:24:43 +0000
Seen: 12 times
Last updated: Jul 20 '23