public class CanonicalURL extends WCMUsePojo {
public LinkCreator linkCreatorUtil;
public String path;
public void activate() throws Exception {
linkCreatorUtil = getSlingScriptHelper().getService(LinkCreator.class);
path = get("path", String.class);
if (path == null) {
path = getCurrentPage().getPath();
}
}
can some one help in writing junit test case for this?
because mocking getSlingScriptHelper() is not working.
lenient().when(wcmUsePojo.getSlingScriptHelper()).thenReturn(slingScriptHelper);
lenient().when(slingScriptHelper.getService(LinkCreator.class)).thenReturn(linkCreator);
Solved! Go to Solution.
Views
Replies
Total Likes
You can mock getSlingScriptHelper like below:
@Mock
private Bindings bindings;
@Mock
private SlingScriptHelper slingScriptHelper;
@BeforeEach
void setUp() {
Mockito.when(bindings.get("sling")).thenReturn(slingScriptHelper);
Mockito.when(slingScriptHelper.getService(LinkCreator.class))
.thenReturn(linkCreator);
canonicalURL.init(bindings);
}
java.lang.NullPointerException: Cannot invoke "javax.script.Bindings.get(Object)" because "this.bindings" is null
at com.adobe.cq.sightly.WCMUsePojo.get(WCMUsePojo.java:110)
at com.adobe.cq.sightly.WCMUsePojo.getSlingScriptHelper(WCMUsePojo.java:283)
at com.morganstanley.mscommons.core.CanonicalURLTest.testActivate_WithPath(CanonicalURLTest.java:58)
error im getting while mocking
Hi @SudarshanV1
Please check examples here
You can mock getSlingScriptHelper like below:
@Mock
private Bindings bindings;
@Mock
private SlingScriptHelper slingScriptHelper;
@BeforeEach
void setUp() {
Mockito.when(bindings.get("sling")).thenReturn(slingScriptHelper);
Mockito.when(slingScriptHelper.getService(LinkCreator.class))
.thenReturn(linkCreator);
canonicalURL.init(bindings);
}
Hi @SudarshanV1 ,
Rely on AEM Context while writing unit tests. https://experienceleague.adobe.com/en/docs/experience-manager-learn/getting-started-wknd-tutorial-de...
@ExtendWith({ AemContextExtension.class, MockitoExtension.class })
class YourTest {
private final AemContext aemContext = new AemContext();
@BeforeEach
void init() {
SlingBindings bindings = (SlingBindings) request.getAttribute(SlingBindings.class.getName());
CanonicalURL model = new CanonicalURL();
model.init(bindings);
}
}
Best regards,
Kostiantyn Diachenko.
@SudarshanV1 Did you find the suggestions helpful? Please let us know if you need more information. If a response worked, kindly mark it as correct for posterity; alternatively, if you found a solution yourself, we’d appreciate it if you could share it with the community. Thank you!
Views
Replies
Total Likes
Views
Likes
Replies
Views
Likes
Replies
Views
Likes
Replies
Views
Likes
Replies