Menu

JUnit for Java getter and setter methods

 

POJO class

public class ColleagueDetails {
private String colleagueID;
private String colleagueEmail;
public ColleagueDetails(String colleagueID, String colleagueEmail) {
this.colleagueID = colleagueID;
this.colleagueEmail = colleagueEmail;
}
public String getColleagueID() { return colleagueID; }
public void setColleagueID(String colleagueID) { this.colleagueID = colleagueID; }
public String getColleagueEmail() { return colleagueEmail; }
public void setColleagueEmail(String colleagueEmail) { this.colleagueEmail = colleagueEmail; }
}

Test class
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.*;

class ColleagueDetailsTest {
ColleagueDetails colleagueDetails = new ColleagueDetails("1234", "email@jorvee.com");

@BeforeEach
void setUp() { }

@Test
void getColleagueIDTest() {
colleagueDetails.setColleagueID("1234");
assertEquals("1234", colleagueDetails.getColleagueID());
}

@Test
void getColleagueEmailTest() {
colleagueDetails.setColleagueEmail("email@jorvee.com");
assertEquals("email@jorvee.com", colleagueDetails.getColleagueEmail());
}

}

JUnit for AEM sling model class with adaptables SlingHttpServletRequest

Sling Model class

We have this sling model class for that we are going to write unit test using JUnit5.


@Model(adaptables = SlingHttpServletRequest.class, 
defaultInjectionStrategy = DefaultInjectionStrategy.OPTIONAL)
public class LinkCheckerModel {
@Inject
@Named("link")
@Source("request-attributes")
private String link;

@Inject
@Source("sling-object")
private ResourceResolver resolver;

private boolean isExternal;

private String updatedLink;
    private final static String DOT_HTML = ".html";
private final Logger logger = LoggerFactory.getLogger(getClass());

@PostConstruct
public void init() {
try {
isExternal = false;
if(StringUtils.isNotBlank(link)) {
if (!isInternal(link)) {
isExternal = true;
updatedLink = link;
} else {
link = link.contains(DOT_HTML) ? link : (link + DOT_HTML);
updatedLink = resolver.map(link);
}
}
} catch (Exception e) {
logger.error("Exception occurs while checking link:{}", e.getMessage());
}
logger.info("Exit init method of Linkchecker Model");
}

private boolean isInternal(String linkStr) {
return linkStr.startsWith("/content") && !linkStr.startsWith("/content/dam");
}
public boolean isExternal() {
return isExternal;
}
public String getUpdatedLink() {
return updatedLink;
}
}

Test class

Generate or create the test class of our sling model class. In this case we have class LinkCheckerModel and created Test class LinkCheckerModelTest.java.

Note: Right click on the class name and choose the option to generate the test. Then select the methods for that you want to create test methods.


import io.wcm.testing.mock.aem.junit5.AemContext;
import io.wcm.testing.mock.aem.junit5.AemContextExtension;
import org.apache.commons.lang3.StringUtils;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.resource.Resource;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;

import static org.junit.jupiter.api.Assertions.*;

@ExtendWith(AemContextExtension.class)
class LinkCheckerModelTest {
private AemContext context = new AemContext();
@Mock
private SlingHttpServletRequest request;
LinkCheckerModel linkCheckerModel = new LinkCheckerModel();
@BeforeEach
void setUp() {
context.load().json("/linkChecker.json", "/content/jorvee/en");
context.addModelsForClasses(LinkCheckerModel.class);
Resource resource = context.resourceResolver().
getResource("/content/jorvee/en/jcr:content/parsys/linkCheckerNode");
        linkCheckerModel = context.request().adaptTo(LinkCheckerModel.class);

linkCheckerModel.init();
}

@Test
void initTest() {

}

@Test
void isExternalTest() {
assertNotNull(linkCheckerModel.isExternal());
}

@Test
void getUpdatedLinkTest() {
assertNull(linkCheckerModel.getUpdatedLink());
}
}


JSON data [linkChecker.json]

The JSON data on which we will mock the request. Create a JSON file with name linkChecker.json and add this json object into that.

{
"jcr:primaryType": "cq:Page",
"jcr:content": {
"cq:contextHubPath": "/etc/cloudsettings/default/contexthub",
"cq:contextHubSegmentsPath": "/etc/segmentation/contexthub",
"cq:designPath": "/etc/designs/jorvee",
"cq:lastModified": "{Date}2020-04-14T19:23:41.457+05:30",
"cq:lastModifiedBy": "admin",
"cq:lastReplicated": "{Date}2020-02-10T19:55:14.981Z",
"cq:lastReplicatedBy": "admin",
"cq:lastReplicationAction": "Activate",
"cq:template": "/apps/jorvee/templates/basic",
"jcr:primaryType": "cq:PageContent",
"jcr:title": "Jorvee | Homepage",
"releaseDate": "Wed Apr 01 2020 00:00:00 GMT+0530",
"sling:resourceType": "jorvee/components/pages/basic/v1/basic",
"section": "sect",
"parsys": {
"jcr:primaryType": "nt:unstructured",
"sling:resourceType": "wcm/foundation/components/parsys",
"linkCheckerNode": {
"jcr:primaryType": "nt:unstructured",
"sling:resourceType": "jorvee/components/buttons/linkChecker",
"link": "/content/jorvee"
}
}
}
}

Run the test

You are all set and now it's time to test the class and methods. You can run the testclass from run option of the IDE. also you can run the test calss using maven command for just a single class.

mvn test -Dtest=<className>

e.g. mvn test -Dtest=LinkCheckerModelTest


Junit Tutorials

 

Difference between s.t() and s.tl() send data | Analytics

- s.t(): Send data to Adobe Analytics and treat it as a page view

- s.tl(): Send data to Adobe Analytics and do not treat it as a page view


Learn Analytics Basic to Advance