'How to mock bean with @PostConstruct method
I need to mock some class that contains @PostConstruct method, but I get NullPointerException inside @PostConstruct method.
My code looks like the following:
@SpringJUnitConfig(MyTestClass.Config.class)
class MyTestClass {
@Autowired
MyClass myClass;
@Autowired
MyService service;
@Test
void testService() {
assertNotNull(myClass);
}
@Configuration
static class Config {
@Bean
MyService service(MyClass myClass) {
return Mockito.spy(new MyService(myClass));
}
@Bean
MyClass myClass() {
return mock(MyClass.class);
}
@Bean
ObjectMapper mapper() {
return new ObjectMapper();
}
}
}
public class MyClass {
private ObjectMapper mapper;
@Autowired
public MyClass(ObjectMapper mapper) {
this.mapper = mapper;
}
@PostConstruct
void init() {
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, true); // I get NPE bacause mapper is null.
}
}
How can I avoid this exception? I can't use @MockBean, because I have to inject this mock into another bean.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
