Java JMockit 模拟构造函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18540627/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JMockit mock constructor
提问by userx
I am unit testing a class which has a complicated constructor ( with lots of parameters ). Constructor takes three arguments like :
我正在对一个具有复杂构造函数(带有很多参数)的类进行单元测试。构造函数采用三个参数,如:
public BehavioralDischargeCarePlan_Bus(Webform webForm,String dataEntryModel, String obsBatId) {
super(webForm, dataEntryModel, obsBatId);
.....
The constructor then calls a super constructor which gets even more complex. Using JMockit, how can I create an instance of the class and test a method without actually invoking the constructors ? I am new to JMockit, any help will be appreciated.
构造函数然后调用一个超级构造函数,它变得更加复杂。使用 JMockit,如何在不实际调用构造函数的情况下创建类的实例并测试方法?我是 JMockit 的新手,任何帮助将不胜感激。
Thanks !
谢谢 !
采纳答案by joescii
If I've understood you correctly, you want to test a class with a mocked constructor. This is not a good approach to testing because you aren't testing the production code in its purest form.
如果我对你的理解正确的话,你想用一个模拟的构造函数来测试一个类。这不是一种很好的测试方法,因为您没有以最纯粹的形式测试生产代码。
However, not everything goes according to the rules, does it? :) So if you insist, JMockIt will let you do this. You can mock out just the constructor and test the other methods. Mocking constructors is well-documented at the JMockIt project site.
然而,并非一切都按照规则进行,不是吗?:) 所以如果你坚持,JMockIt 会让你这样做。您可以只模拟构造函数并测试其他方法。Mocking 构造函数在JMockIt 项目站点中有详细记录。
Here is a quick demonstration you can try yourself:
这是您可以自己尝试的快速演示:
Production code:
生产代码:
// src/main/java/pkg/SomeClass.java
public class SomeClass {
public static void main(String[] args) {
new SomeClass("a", 2);
}
public SomeClass(String a, Integer b) {
System.out.println("Production constructor called");
}
}
Mock code:
模拟代码:
// src/test/java/pkg/SomeMock.java
import mockit.Mock;
import mockit.MockUp;
public class SomeMock extends MockUp<SomeClass> {
@Mock
public void $init(String a, Integer b) {
System.out.println("Mock constructor called");
}
}
Test code:
测试代码:
// srce/test/java/pkg/SomeTest.java
import org.junit.Test;
public class SomeTest {
@Test
public void test() {
new SomeMock();
new SomeClass("a", 2);
}
}
Running the production code will print Production constructor called
, but running it under test will print Mock constructor called
.
运行生产代码将打印Production constructor called
,但在测试下运行将打印Mock constructor called
。