考虑以下代码:
@Tested
CodeToTest codeToTest;
@Injectable
Injected injected;
@Test
public void test() {
new Expectations() {{ ... }}
assertThat(codeToTest.memberVariable).isEqualTo("x");
}
//
public class CodeToTest { public CodeToTest(Injected injected) { memberVariable = injected.getProperty("x") } }
我想测试 CodeToTest。 CodeToTest 需要 Injected 才能注入(inject)到它的构造函数中。如何设置 injected.setProperty("x") 等属性,以便在 CodeToTest 中访问它?
最佳答案
手头的测试应该覆盖 CodeToTest
的特定方法;构造函数应该像您的测试一样有自己的测试。因此,例如,如果构造函数根据传入的内容设置字段,如下所示:
public class Bar {
public int getValue() {
return 8675309;
}
}
public class Foo {
public String field = null;
public Foo(Bar b) {
this.field = "" + b.getValue();
}
public String getField() {
return this.field;
}
public char getFirstChar() {
return getField().charAt(0);
}
}
在这里,我根据在传递给构造函数的 Bar
中找到的 int
设置一个 String
字段。我希望对我的 getFirstChar()
方法进行单元测试 ...
@Tested Foo foo;
@Injectable Bar bar;
@Test
public void test() throws Exception {
// ...
}
现在,正如您所指出的,在这种情况下,我的 field
甚至在 test()
开始之前就已经设置好了。所以我在这里有两个选择:首先,因为我要根据它的 getter 提取 field
,所以我可以部分地模拟我正在测试的类:
@Test
public void test() throws Exception {
new Expectations(foo) {{
foo.getField(); result = "24601";
}};
char c = foo.getFirstChar();
assertThat(c, is('2'));
}
或者,如果您不想这样做,或者如果您正在直接访问字段而不是通过 getter,则可以使用 Deencapsulation
(JMockit 的一部分)设置内部字段,然后测试:
@Test
public void test() throws Exception {
Deencapsulation.setField(foo, "field", "24601");
char c = foo.getFirstChar();
assertThat(c, is('2'));
}
当然,我单独测试我的构造函数:
@Test
public void testConstructor() throws Exception {
new Expectations() {{
bar.getValue(); result = 24601;
}};
Foo foo2 = new Foo(bar);
String fieldValue = foo2.getField(); // or use Deencapsulation
assertThat(fieldValue, is("24601"));
}
希望这对您有所帮助,祝您好运!
关于java - JMockit:如何设置可注入(inject)属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33025901/