Spring JUnit: How to Mock autowired component in autowired component

I've got a Spring component I'd like to test and this component has an autowired attribute which I need to change for the purpose of unit testing. The problem is, that the class uses the autowired component inside the post-construct method so I'm not able to replace it(i.e. via ReflectionTestUtils) before it's actually used.

How should I do that?

This is the class I want to test:

public final class TestedClass{

    private Resource resource;

    private void init(){
        //I need this to return different result

And this is the base of a test case:

@ContextConfiguration(locations= "classpath:applicationContext.xml")
public class TestedClassTest{

    private TestedClass instance;

    private void setUp(){
        //this doesn't work because it's executed after the bean is instantiated
        ReflectionTestUtils.setField(instance, "resource", new Resource("something"));

Is there some way to replace the resource with something else before the postconstruct method is invoked? Like to tell Spring JUnit runner to autowire different instance?


You can provide a new testContext.xml in which the @Autowired bean you define is of the type you need for your test.

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
private Resource resource;

// Testing instance, mocked `resource` should be injected here 
private TestedClass testedClass;

public void setUp() throws Exception {
    // Initialize mocks created above
    // Change behaviour of `resource`

Spring Boot 1.4 introduced testing annotation called @MockBean. So now mocking and spying on Spring beans is natively supported by Spring Boot.

You can override bean definitions with mocks with spring-reinject https://github.com/sgri/spring-reinject/

I created blog post on the topic. It contains also link to Github repository with working example.

The trick is using test configuration, where you override original spring bean with fake one. You can use @Primary and @Profile annotations for this trick.

Another approach in integration testing is to define a new Configuration class and provide it as your @ContextConfiguration. Into the configuration you will be able to mock your beans and also you must define all types of beans which you are using in test/s flow. To provide an example :

@ContextConfiguration(loader = AnnotationConfigContextLoader.class)
public class MockTest{
 static class ContextConfiguration{
 // ... you beans here used in test flow
    public MockMvc mockMvc() {
        return MockMvcBuilders.standaloneSetup(/*you can declare your controller beans defines on top*/)
                .addFilters(/*optionally filters*/).build();
 //Defined a mocked bean
    public MyService myMockedService() {
        return Mockito.mock(MyService.class);

 private MockMvc mockMvc;

 MyService myMockedService;

 public void setup(){
  //mock your methods from MyService bean 
  when(myMockedService.myMethod(/*params*/)).thenReturn(/*my answer*/);

 public void test(){
  //test your controller which trigger the method from MyService
  MvcResult result = mockMvc.perform(get(CONTROLLER_URL)).andReturn();
  // do your asserts to verify

Need Your Help

Create local user with PowerShell (Windows Vista)

powershell adsi

I've installed PowerShell recently and one of the first things I started looking for was how to create a new user. After looking for some time I still haven't found this.

Postgresql constraint

postgresql foreign-keys

I cannot seem to get this right, I am trying to modify a field to be a foreign key, with cascading delete... what am i doing wrong?