2016-11-11 23 views
3

我嘗試着開始單元測試一箇中等大小的Xtext項目。如何在Xtext測試中使用不同的對象注入而不是生產環境?

該生成器目前依賴於一些我想在我的測試中嘲笑的外部資源。因此,我通過@Inject將所需的對象注入Generator類。

e.g僞代碼:

class MyGenerator implements IGenerator{ 

@Inject 
ExternalResourceInterface resourceInterface; 

... 

} 

我創建語言RuntimeModule內的實際結合:

class MyRuntimeModule{ 
... 
    @Override 
    public void configure(Binder binder) { 
     super.configure(binder); 

     binder.bind(ExternalResourceInterface .class).to(ExternalResourceProductionAcess.class); 
    } 
... 
} 

這對生產環境中正常工作。

然而,在生成測試用例,我想更換我的嘲笑版的結合,這樣對CompilationTestHelper以下調用使用模擬:

compiler.assertCompilesTo(dsl, expectedJava); 

問:

我在哪裏告訴guice/Xtext綁定注入模擬?

回答

4

如果您使用RunWith和InjectWith註釋您的測試用例,您的測試類將通過特定的IInjectorProvider實現注入。

如果該注入器提供程序使用自定義模塊(如您所示),則使用該配置注入測試用例。但是,您必須確保在整個測試代碼中使用此注射器(例如,您不需要依賴註冊的注射器等)。

查找以下代碼爲例(沒有編譯它,但是這是你必須遵循的基本結構):

@RunWith(typeof(XtextRunner)) 
@InjectWith(typeof(LanguageInjectorProvider)) 
public class TestClass { 

@Inject 
CompilationTestHelper compiler 

... 
} 
+0

感謝您的回答。當使用生成的InjectorProvider時,我的自定義模塊被加載。但是,由於InjectorProvider使用MyRuntimeModule進行綁定,所以ExternalResourceProductionAccess被加載,而不是我的模擬。我試圖編寫一個自定義的InjectorProvider導致XText不加載其注入的資源。 – lwi

+0

幾年前,我定製了由VIATRA中的Xtext生成器生成的InjectorProvider。也許你可以看看它:http://git.eclipse.org/c/viatra/org.eclipse.viatra.git/tree/query/tests/org.eclipse.viatra.query.patternlanguage.emf.tests /src/org/eclipse/viatra/query/patternlanguage/emf/tests/EMFPatternLanguageInjectorProvider.java –

相關問題