相关疑难解决方法(0)

如何使用EasyMock模拟从抽象类继承的方法?

我正在与EasyMock挣扎.我写了两个小班来说明我的问题:

public abstract class A {
    private AtomicReference<Integer> id = new AtomicReference<Integer>(null);
    public final int getId() {
        return id.get();
    }
    public final boolean setId(int id) {
        return this.id.compareAndSet(null, id);
    }
}

public class B extends A {
}
Run Code Online (Sandbox Code Playgroud)

然后我继续写一个测试方法如下:

public class EasyMockTester extends EasyMockSupport {
    @Test
    public void test() {
        B b = EasyMock.createStrictMock(B.class);
        EasyMock.expect(b.getId()).andReturn(100);
        replayAll();
        int id = b.getId();
        System.out.println("The ID is: " + id);
        verifyAll();
    }
}
Run Code Online (Sandbox Code Playgroud)

问题是我希望EasyMock简单地模拟一个B类实例(我的实际类不是空的,而是为从抽象类继承的方法添加更多方法).相反,EasyMock实际上会进入A类的代码并开始抱怨NullPointerException.如何让EasyMock模拟扩展抽象类的类?

当我运行此测试时,我得到以下故障跟踪:

在显示java.lang.NullPointerException com.my.project.package.tests.A.getId(A.java:9)在com.my.project.package.tests.EasyMockTester.test(EasyMockTester.java:11)​​在阳光下.在sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)的sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)的java.lang.reflect.Method.invoke上的reflect.NativeMethodAccessorImpl.invoke0(Native Method) Method.java:597)在org.junit.runners.model.FrameworkMethod $ 1.runReflectiveCall(FrameworkMethod.java:44)在org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)的组织.在org.junit.runners.BlockJUnit4ClassRunner.runNotIgnored(BlockJUnit4ClassRunner)的org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)中的junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41). java:79)org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:71)at org.junit.runners.BlockJUnit4Class Runner.runChild(BlockJUnit4ClassRunner.java:49)在org.junit.runners.ParentRunner …

java extends easymock class abstract

5
推荐指数
1
解决办法
4331
查看次数

标签 统计

abstract ×1

class ×1

easymock ×1

extends ×1

java ×1