2015-04-03 254 views
1

在JMockit的JUnit测试中,我使用@Injectable注释来初始化通过Spring DI初始化的生产代码中的字段。为什么JMockit的@Injectable不适用于所有相关领域?

我在几个类中使用了一个类型的实现。 为什么不是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这种方式对多个字段中的测试类来扩展其被测试的单元?

+0

我在这个测试中没有得到任何空引用。 'D'通过测试类中相应的@ @ Injectable'字段设置的所有三个字段'a','b'和'c'实例化。请注意,在这种情况下使用'fullyInitialized = true'不起作用,因为'@ Tested'类中的所有字段都具有匹配的@ @ Injectable's。 – 2015-04-05 01:28:00

+0

@Rogério:感谢您的反馈。你是对的。不过,我已经添加了缺少的代码部分,为您提供了测试用例的完整图片,以便您可以检查其失败的原因。 – 2015-04-06 19:56:32

回答

0

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