Stub only one private static method in a class

Maxsteel :

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)  
    }
}
second :

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"));
    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=143654&siteId=1