How to inject mocked dependencies with jmockit

后端 未结 1 1508
有刺的猬
有刺的猬 2021-02-15 23:48

Currently I try to understand how the @Injectable and @Tested annotations are working. I already did some tests and understood the concept but I didn\'

相关标签:
1条回答
  • 2021-02-16 00:27

    Good question. The thing to notice about JMockit's (or any other mocking API) support for dependency injection is that it's meant to be used only when the code under test actually relies on the injection of its dependencies.

    The example Translator class does not rely on injection for the TranslatorWebService dependency; instead, it obtains it directly through internal instantiation.

    So, in a situation like this you can simply mock the dependency:

    public class TranslatorTest {
        @Tested Translator tested;
        @Mocked TranslatorWebService transWebServiceDependency;
    
        @Test public void translateEnglishToGerman() {
            new Expectations() {{
                transWebServiceDependency.performTranslation("House");
                result = "Haus";
            }};
    
            String translated = tested.translateEnglishToGerman("House");
    
            assertEquals("Haus", translated);
        }
    }
    
    0 讨论(0)
提交回复
热议问题