Search code examples
javaunit-testingmockingmockitopowermockito

How to test a void function with sequential calls


How can one test a function that does not return a value, but uses given arguments to construct some values which are being sent to a sequential function?

For example

public void handleSomeEvent(String str1, String str2){
   MyObject obj1 = new MyObject();
   obj1.setParameterA(str1);
   obj2.setParameterB(str2);
   EventHandler.getInstance().notify(obj1)
}

In the above example i would like to verify EventHandler.notify was called with an object containing str1 as parameterA and str2 as parameter2. Can this be done using some common mocking frameowrk (i.e mockito)?


Solution

  • You can do following

    @RunWith(PowerMockRunner.class)
    @PrepareForTest({ EventHandler.class })
    public class UnderTestTest {
    
    @Test
    public void testLoadUniqueOrNull() throws NKFException {
        PowerMockito.mockStatic(EventHandler.class);
    
        EventHandler handler = PowerMockito.mock(EventHandler.class);
        PowerMockito.when(EventHandler.getInstance())
                .thenReturn(handler);
    
        ArgumentCaptor<MyObject> handlerArg = 
        ArgumentCaptor.forClass(MyObject.class);
        PowerMockito.doNothing()
                .when(handler)
                .notify(handlerArg.capture());
    
        new UnderTest().handleSomeEvent("test");
        Assert.assertEquals(new MyObject("test"), handlerArg.getAllValues()
                .get(0));
    }
    
    }
    
    
    public class UnderTest {
        public void handleSomeEvent(String str1) {
            MyObject obj1 = new MyObject(str1);
    
            EventHandler.getInstance()
                    .notify(obj1);
        }
    }
    
    
    public class MyObject {
    
        private final String x;
    
        public MyObject(String x) {
            this.x = x;
        }
    
        @Override
        public boolean equals(Object obj) {
            return ((MyObject) obj).x == x;
        }
    }
    
    
    public class EventHandler {
    
        private final static EventHandler e = new EventHandler();
    
        public static EventHandler getInstance() {
            return e;
        }
    
        public void notify(MyObject obj) {
            // whatever
        }
    }
    

    (side note this quick code is to demonstrate the functionality not best practises in coding)