Java 如何抑制构造函数中的私有方法调用?

Java 如何抑制构造函数中的私有方法调用?,java,unit-testing,mocking,powermock,Java,Unit Testing,Mocking,Powermock,我有一个非常简单的类,它有一个私有方法。问题是如何抑制此方法调用 这是我的密码: public class Example { private int value; public Example(int value) { this.value = value; method(); } private void method() { throw new RuntimeException(); }

我有一个非常简单的类,它有一个私有方法。问题是如何抑制此方法调用

这是我的密码:

public class Example { 
    private int value;

    public Example(int value) {
        this.value = value;
        method();
    }

    private void method() {
        throw new RuntimeException();
    }

    public int getValue() {
        return value;
    }
}
和测试代码(至少尝试):

UPD

对我来说,遵守这两个条款很重要:

  • PowerMockito.doNothing().when(Example.class,“method”)
  • PowerMockito.verifyPrivate(Example.class,times(1)).invoke(“方法”)

  • 因为您无法修改测试中的代码。我认为没有一个完美的解决方案。您需要部分模拟
    示例
    实例

    List list = new LinkedList();
    List spy = spy(list);
    //You have to use doReturn() for stubbing
    doReturn("foo").when(spy).get(0);
    
    但是你不能这样做,因为你必须先实例化你的对象


    因此,我提出以下由两个测试组成的解决方案。第一个测试从类中删除私有
    方法
    ,实例化
    示例
    ,并验证
    示例
    是否正确初始化。 第二个测试实例化
    示例
    ,并验证
    运行时异常
    (私有
    方法
    的副作用)


    你到底为什么要抛出一个新的异常?我不明白。
    //method()
    应该做trickIt只是一个真实类的例子。@Aaron你可以做什么,不可以做什么?好的,我想他是在问如何模拟
    方法
    ,这样就不会调用它的实际实现了。这是一个“我如何编写这个单元测试?”的问题。实际上,我还需要验证是否调用了该方法(没有调用)。嗯,使用powermock/mockito是不可能的。可能您可以使用
    List list = new LinkedList();
    List spy = spy(list);
    //You have to use doReturn() for stubbing
    doReturn("foo").when(spy).get(0);
    
    import static org.junit.Assert.assertEquals;
    import static org.powermock.api.support.membermodification.MemberMatcher.method;
    import static org.powermock.api.support.membermodification.MemberModifier.suppress;
    
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.powermock.api.mockito.PowerMockito;
    import org.powermock.core.classloader.annotations.PrepareForTest;
    import org.powermock.modules.junit4.PowerMockRunner;
    
    @RunWith(PowerMockRunner.class)
    @PrepareForTest(Example.class)
    public class ExampleTest {
        @Test
        public void constructor_should_initialize_the_v2alue() throws Exception {
            suppress(method(Example.class, "method"));
    
            final int EXPECTED_VALUE = 1;
            Example example = PowerMockito.spy(new Example(EXPECTED_VALUE));
            int RETRIEVED_VALUE = example.getValue();
    
            assertEquals(RETRIEVED_VALUE, EXPECTED_VALUE);
        }
    
        @Test(expected=RuntimeException.class)
        public void constructor_should_invoke_the_private_method() throws Exception {
            new Example(1);
        }
    }