I am writing unit test cases for following class which extends WCMUsePOJO. Now, this class is using a getSlingScriptHelper method shown below.
public class ConstantsServiceProvider extends WCMUsePojo {
private static final Logger logger = LoggerFactory.getLogger(ConstantsServiceProvider.class);
private String var1;
@Override
public void activate() throws Exception {
ConstantsService constantsService = getSlingScriptHelper().getService(ConstantsService.class);
if(constantsService != null) {
var1 = constantsService.getVar1();
}
}
public string getVar1() { return var1; }
}
The question is how do I mock getSlingScriptHelper method? Following is my unit test code.
public class ConstantsServiceProviderTest {
@Rule
public final SlingContext context = new SlingContext(ResourceResolverType.JCR_MOCK);
@Mock
public SlingScriptHelper scriptHelper;
public ConstantsServiceProviderTest() throws Exception {
}
@Before
public void setUp() throws Exception {
ConstantsService service = new ConstantsService();
scriptHelper = context.slingScriptHelper();
provider = new ConstantsServiceProvider();
provider.activate();
}
@Test
public void testGetvar1() throws Exception {
String testvar1 = "";
String var1 = provider.getVar1();
assertEquals(testvar1, var1);
}
}
You shouldn't create a mock for
ConstantsServiceProvider.classif you want to unit-test it. Instead, you should create mocks of its internal objects. So:ConstantsServiceProviderwithnewgetSlingScriptHelper().getService(.)methods. Usually, dependencies are provided (injected) to classes by some container likeSpringor simply provided by other classes of your app using setters. In both cases mocks creation is easy.void activate()method which doesn't return anything. So, you should verify callingconstantsService.getVar1()method.I strongly advice you to study Vogella unit-testing tutorial