Ask Your Question
3

How can you replace a bean in the runtime configuration of SpringBootTest?

asked 2023-07-20 12:24:43 +0000

nofretete gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2023-07-20 12:32:01 +0000

woof gravatar image

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.

edit flag offensive delete link more

Your Answer

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

Add Answer


Question Tools

Stats

Asked: 2023-07-20 12:24:43 +0000

Seen: 12 times

Last updated: Jul 20 '23