1

I have a class that I am unit testing. It looks like following:

 public class classToUT {
         public static Event getEvent(String id) {
                return getEvent(id, null);
         }
         private static Event getEvent(String id, String name) {
              //do something
              logEvent(id, name);
              return event;
         }
         private static void logEvent(String id, string name) {
             // do some logging
         }
    }

There are external util methods being called in logEvent that I want to avoid. Basically, I want only logEvent to be stubbed out but all other methods to be called in my unit test. How do I stub out this one method only?

public void UTClass {
    @Test
    public void testGetEvent() {
         assertNotNull(event, classToUt.getEvent(1)); //should not call logEvent 
        //but call real method for getEvent(1) and getEvent(1, null)  
    }
}
Maxsteel
  • 1,922
  • 4
  • 30
  • 55
  • 1
    possible duplicate - https://stackoverflow.com/questions/4860475/powermock-mocking-of-static-methods-return-original-values-in-some-particula – second Jul 23 '19 at 22:36
  • While the above works for returning a value, I can't figure out a way for it to make it work for do nothing() – Maxsteel Jul 23 '19 at 22:38

1 Answers1

3

Try the following ...

@RunWith(PowerMockRunner.class)
@PrepareForTest(PowerTest.ClassToUT.class)
public class PowerTest {

    public static class ClassToUT {

        public static String getEvent(String id) {
            return getEvent(id, null);
        }

        private static String getEvent(String id, String name) {
            // do something
            logEvent(id, name);
            return "s";
        }

        private static void logEvent(String id, String name) {
            throw new RuntimeException();
        }
    }

    @Test
    public void testGetEvent() throws Exception {

        PowerMockito.spy(ClassToUT.class);
        PowerMockito.doNothing().when(ClassToUT.class, "logEvent", any(), any());

        Assert.assertEquals("s", ClassToUT.getEvent("xyz"));
    }
}
second
  • 4,069
  • 2
  • 9
  • 24