Reputation: 49
Usually I use @MockBean annotation to any JPA repository services and works fine. But I tried to use @MockBean with RestTemplate object which was getting created in the Configuration class and it didnt work.
@SpringBootApplication
@EnableAutoConfiguration
@PropertySource(value = "file:/etc/secrets/dbConfig.properties", ignoreResourceNotFound = true)
public class Configuration extends SpringBootServletInitializer {
@Bean
public RestTemplate getRestTemplate() {
return new RestTemplate();
}
}
Service Class looks something like this :
@Service
public class TransitCalculatorService {
@Autowired
RestTemplate restTemplate;
@Autowired
TransitDropdownInfoRepository transitDropdownInfoRepository;//MockBean works fine
}
In the Test Class I did something like this:
@Test
public class TransitCalTest2 {
@MockBean
private RestTemplate restTemplate;
@MockBean
TransitDropdownInfoRepository transitDropdownInfoRepository;
@Autowired
private TransitCalculatorService transitCalculatorService;
....
}
I got this error :
java.lang.IllegalStateException: Failed to load ApplicationContext ... Caused by: java.lang.IllegalStateException: Unable to register mock bean org.springframework.web.client.RestTemplate expected a single matching bean to replace but found [getRestTemplate, restTemplate]
I understood the problem. I added @Primary like this and it worked:
@Bean
@Primary
public RestTemplate getRestTemplate() {
return new RestTemplate();
}
What I didnt understand is the behavior. Why JPA methods transitDropdownInfoRepository can be mocked without declaring @Primary? And why Spring got confused with a MockedBean and an actual Bean? Please someone explain in details. Thank you so much in advance.
Upvotes: 1
Views: 224