【发布时间】:2015-04-03 16:18:06
【问题描述】:
在使用 JMockit 的 JUnit 测试中,我使用 @Injectable 注释来初始化生产代码中通过 Spring DI 初始化的字段。
我在几个类中使用一个类型的实现。
为什么C 不作为IC 的实现注入A 类型的模拟中,就像在下面提到的测试方法中注入B 和D 类型一样?
@Service
@Scope("prototype")
public class A {
@Autowired IC c;
public IC getC() { return c; }
// do something using C in the method body
public void doSomething() {}
}
@Service
@Scope("prototype")
public class B {
@Autowired IC c;
public IC getC() { return c; }
// do something using C in the method body
public void doSomething() {}
}
public interface IC { void doSomething(); }
@Service
@Scope("prototype")
public class C implements IC {
@Override
public void doSomething() {}
}
@Service
public class D {
@Autowired IC c;
@Autowired B b;
@Autowired A a;
public IC getC() { return c; }
public B getB() { return b; }
public A getA() { return a; }
}
public class TestClass {
@Tested(fullyInitialized = true) D d;
@Injectable IC c;
@Tested @Injectable A a;
@Tested @Injectable B b;
@Test
public void test() {
// expectations are recorded here
assertNotNull(d.getC());
assertNotNull(d.getB().getC());
// Null reference
assertNotNull(d.getA().getC());
}
}
编辑:
@Tested 和 C 的用例已添加到代码示例中。该注解已用于将C 注入A 和B 以最终在它们的某些方法中使用它。
编辑 2:
测试类中的多个字段是否允许使用@Tested这种方式来扩展被测试的单元?
【问题讨论】:
-
我在这个测试中没有得到任何空引用。
D使用测试类中对应的@Injectable字段设置的所有三个字段a、b和c进行实例化。请注意,在这种情况下使用fullyInitialized = true无效,因为@Tested类中的所有字段都匹配@Injectables。 -
@Rogério:感谢您的反馈。你是对的。但是,我添加了代码的缺失部分,以便为您提供测试用例的完整图片,以便您检查失败的原因。
标签: unit-testing jmockit