在没有记录Expectations的下面的测试用例中,我预计动态部分模拟特性将用于使用@Injectable在UnitToTest中初始化的字段A和B。但是,方法调用总是会被模拟。只有对静态部分模拟使用无效的筛选值,才能调用真正的方法:
@Service
class A {
public String doSomething() { return "doSomething"; }
public String doSomethingElse() { return "doSomethingElse"; }
}
@Service
class B {
public String doSomething() { return "doSomething"; }
public String doSomethingElse() { return "doSomethingElse"; }
}
@Service
class UnitToTest {
@Autowired B b;
@Autowired A a;
public B getB() { return b; }
public A getA() { return a; }
}
public class TestClass {
@Tested UnitToTest unit;
// @Mocked({ "someInvalidFilter()" })
@Injectable A a;
// @Mocked({ "someInvalidFilter()" })
@Injectable B b;
@Test
public void test() {
// actual return value is always null if no invalid static partial
// mocking filters are specified above
assertEquals("doSomething", unit.getA().doSomething());
assertEquals("doSomethingElse", unit.getA().doSomethingElse());
assertEquals("doSomething", unit.getB().doSomething());
assertEquals("doSomethingElse", unit.getB().doSomethingElse());
}
}对我来说,使用JMockit进行动态部分模拟似乎不适用于@Injectable。这是已知的限制吗?
发布于 2015-04-08 16:05:35
假设可以找到匹配的字段或构造函数参数,@Injectable总是被注入到@Tested对象中;注入过程甚至考虑到DI注释,如@Inject和@Autowired。
但是,@Injectable实例总是作为未初始化的(即没有状态)和完全模拟的实例创建的。另一方面,部分模拟是针对在测试中实例化(并初始化)的实例。
因此,您似乎要求的是,可以将实际实例(部分模拟与否)注入到@Tested对象中。事实上,这是不受支持的(除了调用Deencapsulation.setField),因为用户从来没有提供过一个有动机的用例。
尽管如此,如果将示例测试更改为以下内容,则示例测试将通过:
public class TestClass {
@Tested(fullyInitialized = true) UnitToTest unit;
@Test
public void test() {
assertEquals("doSomething", unit.getA().doSomething());
assertEquals("doSomethingElse", unit.getA().doSomethingElse());
assertEquals("doSomething", unit.getB().doSomething());
assertEquals("doSomethingElse", unit.getB().doSomethingElse());
}
}上面的测试是集成测试,而不是单元测试。
https://stackoverflow.com/questions/29494959
复制相似问题