类结构如下所示:
class A {
protected String a;
protected String b;
A(String b1) {
new A("A111", b1);
}
A(String a1, String b1) {
a = a1;
b = b1;
}
}
class B extends A {
B(String b) {
super("A", b);
}
}
我需要编写 JUnit 测试用例,并且需要模拟 A 类的构造函数,以便每当需要创建 B 类的对象时,A 类的模拟构造函数应该被调用并从模拟构造函数返回对象。
我尝试了以下操作:
new MockUp<A>() {
@Mock
public void $init(String b1) {
new A("A11111111", b1);
}
};
但是在模拟构造函数中创建的对象尚未返回。
最佳答案
好吧,您走在正确的道路上...它需要 @Mock
、MockUp
、Invocable
和 的组合解封装
...您必须向您的$init
模拟方法添加一个调用
,然后使用解封装来查看A
内部结构。这是一个例子。我使用了您的 A 类和 B 类,只是稍微清理了一下它们并添加了 setter/getter 以方便使用。我故意没有添加 setter,这样我就可以展示如何解决缺少 setter 的问题。
package com.example.dcsohl;
import org.junit.Test;
import mockit.Deencapsulation;
import mockit.Invocation;
import mockit.Mock;
import mockit.MockUp;
public class TestTest {
public static class A {
protected String a;
protected String b;
public A(String b1) {
this("A111", b1);
}
public A(String a1, String b1) {
a = a1;
b = b1;
}
}
public static class B extends A {
public B(String b1) {
super("A", b1);
}
public String getA() {
return this.a;
}
public String getB(){
return this.b;
}
}
@Test
public void test() {
new MockUp<A>() {
@Mock public void $init(Invocation inv, String a1, String b1) {
A a = inv.getInvokedInstance();
Deencapsulation.setField(a, "b", b1);
}
};
B b = new B("foo");
System.out.println(b.getA());
System.out.println(b.getB());
}
}
您会注意到,最后,打印输出显示我成功设置了 b
的值,但是,单独保留 a
后,结果为 空
。
关于java - 如何在Junit中模拟子类的构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32954439/