javaspringspring-bootjunitmockito

Init spring boot mocks before they are injected


Is there a way to initialise mocks before they are injected into another component?

To give an example I have following classes:

@Service
SomeService {
    @Autowired
    public SomeService(SomeConfig config)
}

@Configuration
@Getter
@Setter
public class SomeConfig {
  private String someValue;
}

In my test I'm doing the following:

@MockBean
SomeConfig someConfig;

@Autowired
SomeService someService;

The problem is, that the SomeService constructor is already accessing SomeConfig members, before I can even initialise it with when(someConfig.getSomeValue()).thenReturn("something"), resulting in a NullPtrException.

Is there a hook that gets executed before SomeService is instantiated?


Solution

  • You could manually setup your Service in a setup method.
    Just make sure to exclude your SomeService from classpath scanning in those tests.

    SomeServiceTest {
      @MockBean
      SomeConfig someConfig;
    
      SomeService someService;
    
      @BeforeEach
      public void setup(){
        // init mocks
        // setup other stuff
    
        someService = new SomeService(someConfig);
      }
    
    }