【问题标题】:Why isn't JMockit's @Injectable applied to all relevant fields?为什么 JMockit 的 @Injectable 没有应用于所有相关领域?
【发布时间】:2015-04-03 16:18:06
【问题描述】:

在使用 JMockit 的 JUnit 测试中,我使用 @Injectable 注释来初始化生产代码中通过 Spring DI 初始化的字段。

我在几个类中使用一个类型的实现。 为什么C 不作为IC 的实现注入A 类型的模拟中,就像在下面提到的测试方法中注入BD 类型一样?

@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());
    }
}

编辑: @TestedC 的用例已添加到代码示例中。该注解已用于将C 注入AB 以最终在它们的某些方法中使用它。

编辑 2: 测试类中的多个字段是否允许使用@Tested这种方式来扩展被测试的单元?

【问题讨论】:

  • 我在这个测试中没有得到任何空引用。 D 使用测试类中对应的@Injectable 字段设置的所有三个字段abc 进行实例化。请注意,在这种情况下使用 fullyInitialized = true 无效,因为 @Tested 类中的所有字段都匹配 @Injectables。
  • @Rogério:感谢您的反馈。你是对的。但是,我添加了代码的缺失部分,以便为您提供测试用例的完整图片,以便您检查失败的原因。

标签: unit-testing jmockit


【解决方案1】:

此功能已在 jmockit 1.25 中修复。确保您使用的是最新版本。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-07-22
    • 1970-01-01
    • 2023-01-18
    • 1970-01-01
    • 2021-02-19
    • 2013-03-31
    • 1970-01-01
    相关资源
    最近更新 更多