How to make mocking dependencies using jmockit

I'm currently trying to understand how @Injectable and @Tested annotations work. I already conducted some tests and understood the concept, but I did not understand how to use this functionality in real applications. Say we are developing a language translator class that depends on a web service. Web service methods are encapsulated in a class class:

// class to test public class Translator() { private TranslatorWebService webService; public String translateEnglishToGerman(String word){ webService = new TranslatorWebService(); return webService.performTranslation(word); } } // dependency public class TranslatorWebService { public String performTranslation(String word){ // perform API calls return "German Translation"; } } 

To test the Translator class independently, we would like to make fun of the TranslatorWebService class. In my opinion, the shoud test class is as follows:

 public class TranslatorTest { @Tested private Translator tested; @Injectable private TranslatorWebService transWebServiceDependency; @Test public void translateEnglishToGerman() { new Expectations() {{ transWebServiceDependency.performTranslation("House"); result = "Haus"; }}; System.out.println(tested.translateEnglishToGerman("House")); } } 

When I first ran this test case, I was expecting a "Haus" result. At a second glance, I saw that the line

 webService = new TranslatorWebService(); 

will always override the entered mock instance with the real instance. But how can I avoid this behavior without changing the business logic?

+5
source share
1 answer
Good question. The fact is that support for JMockit (or any other mocking API) for dependency injection is that it is intended to be used only when the test code actually relies on injecting its dependencies.

Example Translator class does not rely on injection for the TranslatorWebService dependency; instead, he receives it directly through an internal instance.

So, in a similar situation, you can just mock the addiction:

 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); } } 
+6
source

Source: https://habr.com/ru/post/1206248/


All Articles