It may be a matter of course for those who know it, but I will show it here because it was a great pain.
There were such repository interfaces.
For unit testing, I created a Configuration class that returns a mock of each repository.
MyConfig.java
@Configuration
public class MyConfig {
@Bean
public MenuRepository menuRepository() {
return Mockito.mock(MenuRepository.class);
}
@Bean
public CategoryRepository categoryRepository() {
return Mockito.mock(CategoryRepository.class);
}
@Bean
public UserRepository userRepository() {
return Mockito.mock(UserRepository.class);
}
}
The test of the injection destination is like this.
MyTest.java
//Abbreviation
public class MyTest {
@Autowired
private MenuRepository menuRepository;
@Autowired
private CategoryRepository categoryRepository;
@Autowired
private UserRepository userRepository;
}
The categoryRepository
@Bean method is called, but no other @Bean method is called.
As a result, only Category Repository
is mocked at the injection destination. .. ..
Looking at the contents of the container, there are only two CategoryRepository
(mock and original) and only one others.
By changing the method name, all @Bean methods are now called safely.
MyConfig.java
@Configuration
public class MyConfig {
@Bean
@Primary
public MenuRepository menuRepositoryBean() {
return Mockito.mock(MenuRepository.class);
}
@Bean
@Primary
public CategoryRepository categoryRepositoryBean() {
return Mockito.mock(CategoryRepository.class);
}
@Bean
@Primary
public UserRepository userRepositoryBean() {
return Mockito.mock(UserRepository.class);
}
}
Also, I got an error saying that the type is on, so I added @Primary
.
Why is this happening ...? ??
Recommended Posts