首页 > 解决方案 > 使用 PowerMockito 模拟私有 void 方法

问题描述

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

这是测试类

@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

编辑部分没有故障跟踪: 故障跟踪:

在此处输入图像描述

请让我知道我犯了什么错误,以及如何使它起作用。

标签: unit-testingmockitopowermockito

解决方案


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

请参阅这篇文章:PowerMock 中的@PrepareForTest 真正意味着什么?

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

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


推荐阅读