使用 PowerMockito 模拟私有 void 方法

Mock a private void method using PowerMockito

public class Abcd {
    
    public String one() {
        System.out.println("Inside method one");
        StringBuilder sb = new StringBuilder();
        two(sb);
        return "Done";
    }
    
    private void two(StringBuilder sb) {
        System.out.println("Inside method two");
    }
}

这里是测试class

@RunWith(PowerMockRunner.class)
@PrepareForTest(Abcd.class)
public class TestAbcd {
    
    @Test
    public void testMethod1() throws Exception {
        Abcd abcd = PowerMockito.spy(new Abcd());
        StringBuilder sb = new StringBuilder();
        PowerMockito.doNothing().when(abcd, "two", sb);
        abcd.one();
    }
}

控制台输出:

Inside method one
Inside method two

编辑部分无故障痕迹: 故障痕迹:

请让我知道我犯了什么错误,我该如何解决。

您需要@PrepareForTest 注释才能使用 PowerMockito 获得对私有方法的这种控制。

查看这篇文章:

总而言之,测试用例应该如下所示:

@RunWith(PowerMockRunner.class)
@PrepareForTest(Abcd.class)
public class TestAbcd {
    
    @Test
    public void testMethod1() throws Exception {
        Abcd abcd = PowerMockito.spy(new Abcd());
        PowerMockito.doNothing().when(abcd, method(Abcd.class, "two", StringBuilder.class))
                .withArguments(any(StringBuilder.class));               
        abcd.one();
    }
}