Issue
How to exclude a Spring Boot Component from running in JUnit unit tests?
What I've tried
Please correct me if I'm wrong. @ComponantScan
is excluding a class globally, both in main & test?
Since I don't want exclude my it globally, only during unit tests, is there any way to do that?
@Component
public class DatabaseInitialization {
@Autowired
private UserRepository userRepository;
@PostConstruct
private void postConstruct() {
User user = new User();
user.setEmail("[email protected]");
user.setPassword("1234567");
user.setFirstName("Charle");
user.setLastName("P.");
user.setIbanCode(2641874);
user.setBicCode(63215472);
user.setFriendsList("[]");
userRepository.save(user);
}
}
Solution
The @MockBean
annotation replaces a bean with another bean implemented by a Mockito mock. You're not going to stub any methods on the mock. You only care that the bean is replaced with a bean that does nothing. Inside your test class:
@SpringBootTest
class MyTest {
@MockBean
private DatabaseInitialization databaseInitialization;
Answered By - Chin Huang