Skip to content

Instantly share code, notes, and snippets.

@davidjgonzalez
Last active February 26, 2019 19:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save davidjgonzalez/4ac2574dbb413d841e7e6d2c6877d3af to your computer and use it in GitHub Desktop.
Save davidjgonzalez/4ac2574dbb413d841e7e6d2c6877d3af to your computer and use it in GitHub Desktop.
package com.adobe.aem.guides.wknd.core.components.impl;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.mockito.Mockito.doReturn;
import static org.mockito.ArgumentMatchers.*;
import org.apache.sling.models.factory.ModelFactory;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import com.adobe.aem.guides.wknd.core.components.Card;
import com.adobe.cq.wcm.core.components.models.Image;
import io.wcm.testing.mock.aem.junit.AemContext;
@RunWith(MockitoJUnitRunner.class)
public class CardImplTest {
@Rule
public AemContext ctx = new AemContext();
@Mock
ModelFactory modelFactory;
@Before
public void setUp() throws Exception {
ctx.addModelsForPackage(Card.class.getPackage().getName(),
Image.class.getPackage().getName());
ctx.load().json("/components/card.json", "/content");
}
@Test
public void testGetLinkPath() {
String expected = "/content/article-page";
ctx.currentResource("/content/card");
Card card = ctx.request().adaptTo(Card.class);
assertEquals(expected, card.getLinkPath());
}
@Test
public void testGetImageSrc() {
final String expected = "/content/article-page/jcr:content/root/image.img.png";
ctx.currentResource("/content/card");
Image image = mock(Image.class);
doReturn(expected).when(image).getSrc();
// This modelFactory is not what's available in the CardImpl's @OsgiService modelFactory... even though
// its registered as a service on the next line
// This results in a call to the "real" (via the magical AEMContext) modelFactory .. which is not what i want, and also fails with an AbstractMethod error, i believe because Image.class is not resolvable in the context of the test.
doReturn(image).when(modelFactory).getModelFromWrappedRequest(ctx.request(),
ctx.resourceResolver().getResource("/content/article-page/jcr:content/root/image"),
Image.class);
ctx.registerService(ModelFactory.class, modelFactory);
card = ctx.request().adaptTo(Card.class);
String actual = card.getImageSrc();
assertEquals(expected, actual);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment