Powermock 不拦截新对象的创建

Powermock not intercepting new object creation

我正在尝试测试一种创建另一个 class 的新实例的方法,我希望使用 powermock 对其进行模拟。我的代码(简化)如下 -

测试代码:

import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

import static org.easymock.EasyMock.anyObject;
import static org.powermock.api.easymock.PowerMock.*;

@RunWith(PowerMockRunner.class)
@PrepareForTest( { ClassUnderTest.class } )
public class TestForClassUnderTest {

    private ClassToBeMocked classToBeMocked;
    private ClassUnderTest classUnderTest;

    public void testSimple() throws Exception {

        classToBeMocked = createMock(ClassToBeMocked.class);
        // trying to intercept the constructor
        // I *think* this is the root cause of the issue 
        expectNew(ClassToBeMocked.class, anyObject(), anyObject(), anyObject()).andReturn(classToBeMocked);

        classToBeMocked.close();
        expectLastCall();
        replayAll();

        // call to perform the test
        classUnderTest.doStuff();
    }
} 

正在测试的代码:

import ClassToBeMocked;

public class ClassUnderTest {
    private ClassToBeMocked classToBeMocked;

    public void doStuff() {

        classToBeMocked = new ClassToBeMocked("A","B","C");
        // doing lots of other things here that I feel are irrelevant
        classToBeMocked.close();
    }
}

我想模拟的代码:

public class ClassToBeMocked {
    public ClassToBeMocked(String A, String B, String C) {
    // irrelevant
    }
    public close() {
    // irrelevant
    }
}

我得到的错误如下:

java.lang.ExceptionInInitializerError

    at ....more inner details of where this goes into

    at ClassToBeMocked.close

    at ClassUnderTest.doStuff

    at TestForClassUnderTest.test.unit.testSimple

Caused by: java.lang.NullPointerException

PowerMock version:1.4.5

EasyMock 版本:3.1

PS:我已将代码精简到最低限度,仅显示模拟库的详细信息,如果您认为我的其他代码有某种干扰,请告诉我,我可以提供更多详细信息您认为重要的部分要展示。执行此操作的其他示例的任何链接甚至可能有所帮助。

每当您想模拟任何 class 的新实例时,您应该这样做

Powermock.expectNew(ClassYouWishToMock.class).andReturn(whateverYouWantToReturn).anyTimes();
Powermock.replayAll();

当在此 class.

上调用 new 时,这将 return 'whateverYouWantToReturn'

但是每当你想模拟一个实例变量时,你应该使用 easymock 的 Whitebox 特性。

看看下面的例子

Class A{
     private B b;
}

为了模拟这个,我的测试 class 看起来像这样

...//other powermock, easymock class level annotations
@PrepareForTest(B.class)
class ATest{
        Whitebox.setInternalState(B.class,b,whateverValueYouWantYourMockedObjectToReflect);
}

这里'b'传入的参数,就是你要mock的变量名。

祝你好运!

我意识到这不起作用的原因是因为我正在扩展另一个 class。我有

@RunWith(PowerMockRunner.class)
@PrepareForTest( { ClassUnderTest.class } )
public class TestForClassUnderTest extends AnotherClass {

}

我一删除扩展,它就起作用了。不确定它是否只是无法使用 powermock 扩展另一个 class 或由于 AnotherClass,但删除它对我有用