2015-04-03 252 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中修復。確保你使用最新版本。