在 class 中仅存根一个私有静态方法

Stub only one private static method in a class

我有一个 class 正在单元测试。看起来像下面这样:

 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
         }
    }

我想避免在 logEvent 中调用外部 util 方法。基本上,我只希望 logEvent 被删除,但在我的单元测试中调用所有其他方法。我如何只删除这一种方法?

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

尝试以下...

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