2016-02-11 42 views
0

爲了向Guice注入一個類,這個替換的類必須作爲一個對象參數傳遞給構造函數嗎?我認爲這是「當然」,但我想我會問。爲了向Guice注入類,被替換的類必須作爲對象參數傳遞給構造函數?

我寫了一個帶有兩個構造函數的被測類(CUT)。一個構造函數接受一個參數,一個類型依賴於組件(DOC)的對象。另一個構造函數調用第一個,傳遞一個新的DOC()。單元測試使用注入器來指示CUT使用MockDOC而不是DOC。當我刪除默認CUT(),單元測試得到一個運行時間錯誤: com.google.inject.internal.ComputationException:java.lang.NoClassDefFoundError:組織/對象式/ ASM/ClassVisitor

的代碼:

//The class under test: 
public class CUT { 
    DOC m_DOC; 

    @Inject 
    public CUT(DOC doc) 
    { 
     m_DOC = doc; 
    } 

    // When this ctor is added, there is a run time error: 
    // com.google.inject.internal.ComputationException: java.lang.NoClassDefFoundError: org/objectweb/asm/ClassVisitor 
// @Inject 
// public CUT() 
// { 
//  this(new DOC()); 
// } 

    public boolean getVal() 
    { 
     return m_DOC.getVal(); 
    } 
} 

    // The depended-on-component: 
public class DOC { 
    @Inject 
    public DOC() 
    { 

    } 

    // The REAL DOC returns 'true' MockDOC will return false 
    public Boolean getVal() 
    { 
     return true; 
    } 
} 

的模擬DOC:

 // This is the class we want CUT to call during unit test 
class MockDOC extends DOC 
{ 
    @Override 
    public Boolean getVal() 
    { 
     // Real DOC returns 'true'. We return false so unit tester knows we got injected 
     return false; 
    } 
} 

使用MockDOC測試CUT單元測試:

// Test the CUT class by substituting a mock for CUT's DOC 
public class CUTTest { 

    @Test 
    public void testGetVal() throws Exception { 
     // Direct Guice to inject our MockDOC for CUT's use of DOC 
     Injector m_injector = Guice.createInjector(new CUTTestModule()); 

     // Ask Guice to create a CUT object 
     CUT cut = m_injector.getInstance(CUT.class); 

     // The DOC returns 'true', while the mock DOC returns 'false. So we'll get 'false' if the injection 
     // succeeded 
     assertEquals(cut.getVal(), false); 
    } 

    // The class that we will pass to Guice to direct its injection 
    class CUTTestModule implements Module { 
     public CUTTestModule() 
     { 
      super(); 
     } 

     @Override 
     public void configure(Binder binder) { 
      binder.bind(DOC.class).to(MockDOC.class); 
     } 
    } 
} 

回答

1

首先,你也可以在田間使用Guice注射。

但是關於你的主要問題......爲什麼要將@Inject註解添加到默認構造函數(沒有參數的那個)呢?沒有要注入的參數。

// When this ctor is added, there is a run time error: 
    // com.google.inject.internal.ComputationException: java.lang.NoClassDefFoundError: org/objectweb/asm/ClassVisitor 
// @Inject 
// public CUT() 
// { 
//  this(new DOC()); 
// } 

我會刪除@Inject

+0

這隱含回答我的(幼稚)的問題。注入只發生在方法的參數(ctor或其他)上。謝謝 –

相關問題