powermock模拟私有方法但不执行私有方法

时间:2014-08-21 16:23:33

标签: java methods private powermock

如何通过公共方法调用的模拟私有方法,但我不希望私有方法的代码执行: 代码:

@RunWith(PowerMockRunner.class)
@PrepareForTest(B.class)
public class A {
    public static void main(String[] args) throws Exception{
        B b = PowerMockito.spy(new B());
        PowerMockito.doReturn("test").when(b,"test");

       // MY PROBLEM: 
       // there: console print "test method" 
       // i just want return "test"  and don't real execute test()
        String t = b.print(); 

        System.out.println(t);
}

}

class B{
    public String print(){
        System.out.println("pp method");
        return test();
    }
    private String test(){
        System.out.println("test method");  
        return "t";
    }

}

1 个答案:

答案 0 :(得分:0)

我已经解决了这个问题! 只是:   模拟(B.class)   doCallRealMethod()。当(...)。withArguments(...)

请勿使用spy()

谢谢大家。