【问题标题】:Mocking object instantiation with new in Java using PowerMock not working使用 PowerMock 在 Java 中使用 new 模拟对象实例化不起作用
【发布时间】:2018-03-15 03:32:07
【问题描述】:

我正在尝试用 Java 对一个类进行单元测试。

这个类的代码:ToBeTested

public class ToBeTested {
    private Collaborator collaborator;

    public ToBeTested() {
        System.out.println("ToBeTested: Constructor");
    }

    public void start() {
        System.out.println("ToBeTested: Start");
        collaborator = new Collaborator();
    }
}

这个类 ToBeTested 依赖于另一个类 Collaborator

类代码:Collaborator

public class Collaborator {

    Collaborator() {
        System.out.println("Collaborator: Constructor");
    }
}

在测试 ToBeTested 类时,我想对 Collaborator 的实例化存根。这是我想模拟的依赖项,我不想调用它的构造函数。

我正在使用 Junit (v4.12) 和 PowerMock (v1.6.1)。

测试类代码:TestToBeTested

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.easymock.annotation.Mock;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

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

@RunWith(PowerMockRunner.class)
@PrepareForTest({ToBeTested.class, Collaborator.class})
public class TestToBeTested {

    @Mock
    private Collaborator collaborator;

    private ToBeTested toBeTested;

    @Before
    public void setUp() throws Exception {
        collaborator = createMock(Collaborator.class);
        expectNew(collaborator.getClass()).andReturn(null);
        toBeTested = new ToBeTested();
    }

    @Test
    public void test() {
        replayAll();

        toBeTested.start();

        verifyAll();
    }

}

我的理解是,这将模拟或存根 Collaborator 并且不应调用它的构造函数。但是,当我运行测试时,我注意到调用了 Collaborator 的原始构造函数。

测试运行的输出:

ToBeTested: Constructor
ToBeTested: Start
Collaborator: Constructor

我对 Java 和 Java 中的单元测试非常陌生,所以如果我在这里犯了一个非常根本的错误,我深表歉意。

在寻找根本原因的过程中,我提到了以下 SO 问题:

非常感谢您提前提供帮助/建议/反馈。

【问题讨论】:

    标签: java unit-testing junit powermock


    【解决方案1】:

    它可能无法正常工作的一个可能原因可能是这一行:

    expectNew(collaborator.getClass()).andReturn(null);
    

    collaborator 是一个模拟实例,这意味着它的“getClass()”方法将返回 Collaborator$CGLIBMockedWithPowermock 或类似的东西——而不是你想要的 Collaborator 类。因此,您只需将该行更改为:

    expectNew(Collaborator.class).andReturn(null);
    

    【讨论】:

    • 有趣的观察!我会试试的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多