Powermock不会拦截新的对象创建

时间:2015-01-25 01:58:18

标签: java unit-testing testing powermock easymock

我正在尝试测试一个方法,该方法创建另一个我希望使用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版本:1.4.5

EasyMock版本:3.1

PS:我已经将代码剥离到最低限度,只显示模拟库的详细信息,如果您认为我的其他代码在某种程度上干扰,请告诉我,我可以提供您认为重要的位的更多详细信息节目。任何这样做的链接都可以提供帮助。

2 个答案:

答案 0 :(得分:2)

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

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

}

一旦我删除了延伸,它就有效了。不确定它是否只能用powermock或AnotherClass扩展另一个类,但删除它对我有用

答案 1 :(得分:0)

每当你想模拟任何一个类的新实例时,你应该这样做

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

这将在此课程中返回'whateverYouWantToReturn'whener new

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

看看下面的例子

Class A{
     private B b;
}

模拟这个我的测试类看起来像这样

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

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

祝你好运!