Search code examples
unit-testingmockitoprivate-methods

How to unit test a public method that calls private method and that in turn calls a web service method


Here's the setup:

 public class ClassToTest{

    public void doSomething(ObjectToWorkOn[] objects){
        doPrivateStuff(objects);
    }

    private void doPrivateStuff(ObjectToWorkOn[] objects){
        List<ObjectToWorkOn> validObjects=new ArrayList<ObjectToWorkOn>();
        for(ObjectToWorkOn obj:objects){
           if(obj.isValid())
           validObjects.add(obj);
        }
        SomeWebService ws=new SomeWebService();
        ws.processObjects(validObjects);
    }

 }

I need to test the public doSomething method to check if invalidObjects are filtered. As you can see it passess the objects to the private doPrivateStuff method. And that method filters out invalid objects and sends valid ones to a web service method. That web service method does not return anything. So I have no clue as to whether only valid objects were sent to the web service method or not. What do you suggest I do to be able to test this case? I'm using Mockito framework for mocking objects.


Solution

  • The main reason you can't test this method is because you create SomeWebService inside your class.

    To solve this, you should inject SomeWebService.

    public class ClassToTest{
        private readonly ISomeWebService someWebService;
    
        public ClassToTest(ISomeWebService someWebService)
        {
            this.someWebService = someWebService;
        }
    
        public void doSomething(ObjectToWorkOn[] objects){
            doPrivateStuff(objects);
        }
    
        private void doPrivateStuff(ObjectToWorkOn[] objects){
            List<ObjectToWorkOn> validObjects=new ArrayList<ObjectToWorkOn>();
            for(ObjectToWorkOn obj:objects){
               if(obj.isValid())
               validObjects.add(obj);
            }
    
            someWebService.processObjects(validObjects);
        }
    }
    

    Now you can mock your ISomeWebService dependency in test and verify that processObjects method was called with right arguments