Expand my Community achievements bar.

SOLVED

How to write J unit test case for AEM Component

Avatar

Level 1

Code For Reference - 

public int[] getMomentYearsArr() {
int[] years = new int[this.moments.size()];
for (int i = 0; i < this.moments.size(); i++) {
OurHistoryMoments moment = this.moments.get(i);
years[i] = moment.getMomentYear();
}
return years;
}
1 Accepted Solution

Avatar

Correct answer by
Community Advisor

Hi @nitish_mishra 
Don't get confused with unit testing for the AEM component. The code snippet you shared seems to be normal java code and you can easily write the Junits for the same with the help of Junits with the mockito framework. These two are very popular dependencies and ideally, your project should have already used this dependency.

Based on the JUnit version used in the project, you can understand what features you can use in test cases. There are plenty of blogs available, you can refer to this https://www.vogella.com/tutorials/Mockito/article.html 

And Just for your information, There is an Open Source project "wcm.io" which provides libraries and extensions for AEM-based applications which give us an easy way to mock things such as resources, AEM pages, OSGi services, and many other things but that can be used when it's required. You can find in-depth detail here https://wcm.io/testing/aem-mock/


Regards,

Arpit Varshney

View solution in original post

3 Replies

Avatar

Community Advisor

Hi @nitish_mishra ,

 

You can write a Junit test case for the above method by doing strict stubbing using Mockito.lenient().

Refer to below blog for a clear understanding

https://aemsimplifiedbynikhil.wordpress.com/tag/mockito/

 

 

 

Avatar

Correct answer by
Community Advisor

Hi @nitish_mishra 
Don't get confused with unit testing for the AEM component. The code snippet you shared seems to be normal java code and you can easily write the Junits for the same with the help of Junits with the mockito framework. These two are very popular dependencies and ideally, your project should have already used this dependency.

Based on the JUnit version used in the project, you can understand what features you can use in test cases. There are plenty of blogs available, you can refer to this https://www.vogella.com/tutorials/Mockito/article.html 

And Just for your information, There is an Open Source project "wcm.io" which provides libraries and extensions for AEM-based applications which give us an easy way to mock things such as resources, AEM pages, OSGi services, and many other things but that can be used when it's required. You can find in-depth detail here https://wcm.io/testing/aem-mock/


Regards,

Arpit Varshney