Search code examples
junit4private-membersspring-beanjmock

How to unit test a void returning method where the fields of the owning class are private and Spring @Autowired


I've been given a task to unit test a class where it's fields are autowired to as Spring beans. The main public method called process returns nothing. Here's the fragment of the class:

 public class AutoRejector{

    @Autowired
    private MNPServicesWrapper mnpWrapper;
    //some more autowired fields

    public void process() {
        List<RequestInfo> requests = mnpWrapper.getNewMnpRequests();
        ........
    }
 }

MNPServicesWrapper is an Interface. During test, I want to provide my own, test implementation that will return some test values when getNewMnpRequests method is invoked.

If I was able to set this field through a constructor or a setter, that would be straight forward. But how do I set the @Autowired field?


Solution

  • You can use mocking frameworks like Mockito and PowerMock. They help to inject mocked objects into your test class. You can then specify the method returns. (They use reflections to inject the test object. You can do the same without using Mockito by using reflections) For your void method you can assert the number of times mnpWrapper.getNewMnpRequests() is called using one of these mocking frameworks.

    Please read further about Mockito, import the JAR and use in your JAVA project.

    The test example of your code in Mockito would be:

      @RunWith(MockitoJUnitRunner.class)
      public class AutoRejectorTest {
        @Mock
        MNPServicesWrapper mnpWrapper;
    
        @InjectMocks
        AutoRejector autoRejector;
    
        @Test
        public void processTest(){
           autoRejector.process();
           //Assert that the getNewMnpRequests method was called exactly once
           Mockito.verify(mnpWrapper,times(1)).getNewMnpRequests();
          }
    }