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.
Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss
Asked: 2023-07-20 12:24:43 +0000
Seen: 12 times
Last updated: Jul 20 '23