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?
source share