Spring JUnit: How to Mock autowired component in autowired component
Spring Boot 1.4 introduced testing annotation called @MockBean
. So now mocking and spying on Spring beans is natively supported by Spring Boot.
You could use Mockito. I am not sure with PostConstruct
specifically, but this generally works:
// Create a mock of Resource to change its behaviour for testing
@Mock
private Resource resource;
// Testing instance, mocked `resource` should be injected here
@InjectMocks
@Resource
private TestedClass testedClass;
@Before
public void setUp() throws Exception {
// Initialize mocks created above
MockitoAnnotations.initMocks(this);
// Change behaviour of `resource`
when(resource.getSomething()).thenReturn("Foo");
}