gpt4 book ai didi

java - Powermock 不拦截新对象的创建

转载 作者:行者123 更新时间:2023-11-28 21:10:59 24 4
gpt4 key购买 nike

我正在尝试测试一种方法,该方法创建我希望使用 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:我已将代码精简到最低限度,仅显示模拟库的详细信息,如果您认为我的其他代码有某种干扰,请告诉我,我可以提供您认为重要的部分的更多详细信息展示。指向执行此操作的其他示例的任何链接甚至可能有所帮助。

最佳答案

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

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

}

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

关于java - Powermock 不拦截新对象的创建,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28132436/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com