提问者:小点点

EasyMock部分模拟私人方法


我有以下场景:

public class ClassA {

    public void methodA(){
        try {
            int result=methodB();
        } catch (IOException e) {
           //Some code here
        }
    }

    private int methodB() throws IOException{
        //Some code here
        return 1;
    }
}

我想在测试中覆盖公共方法methodA()的catch块。我不想更改私有方法的可见性。是否有任何方法可以使用EasyMock实现私有方法的部分模拟?或者有没有办法改变Junit类中私有方法的行为,以便在不使用mocking的情况下抛出异常?

提前谢谢。


共2个答案

匿名用户

您不能单独使用Easymock来实现这一点,您可以使用Easymock和Powermock的组合来实现这一点。然后模拟私有方法的返回值。

匿名用户

要测试catch块,必须告诉EasyMock在调用methodB时抛出异常。

从文档中:

For specifying exceptions (more exactly: Throwables) to be thrown, the object returned 
by expectLastCall() and expect(T value) provides the method andThrow(Throwable throwable).
The method has to be called in record state after the call to the Mock Object for which 
it specifies the Throwable to be thrown.

例子:

expectLastCall().andThrow(new IOException("Now to test catch block..."));