【发布时间】: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 问题:
- PowerMock's expectNew() isn't mocking a constructor as expected
- PowerMock expectNew how to specify the type of the parameters
- Not able to mock constructor using PowerMock
- https://dzone.com/articles/using-powermock-mock
非常感谢您提前提供帮助/建议/反馈。
【问题讨论】:
标签: java unit-testing junit powermock