English 中文(简体)
如何使用PowerMock部分模拟公共方法?
原标题:how to partial mock public method using PowerMock?

以下是我的班级

public class SomeClass {
    public ReturnType1 testThisMethod(Type1 param1, Type2 param2) {
        //some code
        helperMethodPublic(param1,param2);
        //more code follows  
    }   

    public ReturnType2 helperMethodPublic(Type1 param1, Type2 param2) {
        //some code            
    }
} 

因此,在上面的类中,在测试testThisMethod()时,我想部分模拟helperMethodPublic()。

截至目前,我正在做以下工作:

SomeClass someClassMock = 
    PowerMock.createPartialMock(SomeClass.class,"helperMethodPublic");
PowerMock.expectPrivate(someClassMock, "helperMethodPublic, param1, param2).
    andReturn(returnObject);

编译器没有抱怨。因此,我尝试运行我的测试,当代码到达helperMethodPublic()方法时,控件进入该方法并开始执行其中的每一行代码。我该如何防止这种情况发生?

问题回答

另一种不依赖于模拟框架的解决方案是在测试中定义的匿名子类中重写helperMethodPublic:

SomeClass sc = new SomeClass() {
   @Override
   public ReturnType2 helperMethodPublic(Type1 p1, Type2 p2) {
      return returnObject;
   }
};

然后,当您在测试中使用此实例时,它将运行testThisMethod的原始版本和helperMethodPublic的重写版本

我想这是因为杰夫说的话。

试试这个——像其他任何被嘲笑的方法一样设定一个期望:

SomeClass someClassMock = PowerMock.createPartialMock(SomeClass.class,
                                                      "helperMethodPublic");

EasyMock.expect(someClassMock.helperMethodPublic(param1, param2)).
    andReturn(returnObject);

PowerMock.replayAll();

我想这是因为你的“helperMethodPublic”不是私有方法(如PowerMock.expectPrivate)。PowerMock是一个框架,它扩展了其他模拟框架,以添加诸如模拟私有和静态方法(JMock、Mockito等不处理)之类的东西。对公共方法进行部分模拟应该是底层模拟框架处理的事情。





相关问题
Spring Properties File

Hi have this j2ee web application developed using spring framework. I have a problem with rendering mnessages in nihongo characters from the properties file. I tried converting the file to ascii using ...

Logging a global ID in multiple components

I have a system which contains multiple applications connected together using JMS and Spring Integration. Messages get sent along a chain of applications. [App A] -> [App B] -> [App C] We set a ...

Java Library Size

If I m given two Java Libraries in Jar format, 1 having no bells and whistles, and the other having lots of them that will mostly go unused.... my question is: How will the larger, mostly unused ...

How to get the Array Class for a given Class in Java?

I have a Class variable that holds a certain type and I need to get a variable that holds the corresponding array class. The best I could come up with is this: Class arrayOfFooClass = java.lang....

SQLite , Derby vs file system

I m working on a Java desktop application that reads and writes from/to different files. I think a better solution would be to replace the file system by a SQLite database. How hard is it to migrate ...

热门标签