SlideShare a Scribd company logo
1 of 18
JUNIT5
Junit5
UNIT TESTING
AGENDA
Introduction
Set Up JUnit Testing
The Anatomy of a JUnit
INTRODUCTION • JUnit is the most popular Java unit testing framework. An
open-source framework, it’s used to write and run
repeatable automated tests.
WHY UNIT TESTING ?
Unit Test cases are mandatory this days you cannot deploy
your code using Cloud Manager until you have 50% of
code coverage.
• JUnit 5 = JUnit Platform + JUnit Jupiter + JUnit Vintage
• Mockito Testing Framework
• wcm.io Test Framework
• Apache Sling Mocks
https://experienceleague.adobe.com/docs/experience-manager-learn/getting-started-wknd-tutorial-
develop/project-archetype/unit-testing.html?lang=en
SET UP JUNIT TESTING
Create Java file(AbcTest.java) under core/src/test/java/com/verily/core/models/AbcTest.java
Create Json File(Abc.json) under core/src/test/resources/ com/verily/core/Abc.json
To get JSON File http://localhost:4502/content/verily/us/..../searchresult.infinity.json
Generally, The testcase class name starts or ends with Test word and all test methods generally
begins with “test” word.
Matching expected result with actual result.
THE ANATOMY OF A JUNIT
@ExtendWith(AemContextExtension.class)
class EventTest {
private final AemContext aemContext = new AemContext();
private EventTest event;
@BeforeEach
void setUp() {
aemContext.addModelsForClasses(Event.class);
aemContext.load().json("/com/mySite/core/models/about.json", "/component");
Resource resource = aemContext.currentResource("/component/event");
event=aemContext.request().adaptTo(Event.class);
}
@Test
void testGetEmail() {
final String expected = "abc@gmail.com";
assertEquals(expected, event.getEmail());
}
@Test
void testGetAddress() {
final String expected = "India"; assertEquals(expected, event.getAddress());
}
}
{
"event": {
"email":"abc@gmail.com",
"address": "india"
}
}
Setting up AEM test context :
import org.junit.jupiter.api.extension.ExtendWith;
import io.wcm.testing.mock.aem.junit5.AemContext;
import io.wcm.testing.mock.aem.junit5.AemContextExtension;
...
@ExtendWith(AemContextExtension.class)
class SearchResultTest {
private final AemContext aemContext = new AemContext();
private String MOCK_RESOURCE = "/com/verily/core/models/SearchResult.json";
private String PAGE_PATH = "/content/verily/us/en";
• AemContextExtension context can be injected into a Junit test using a custom Junit
Extension named AemContextExtension.
• The SearchResultTest Sling Model is registered into this context
• Mock JCR content structures are created in this context
• Custom OSGi services can be registered in this context
• Provides various common required mock objects and helpers such as
SlingHttpServletRequest objects, various mock Sling and AEM OSGi services such as
ModelFactory, PageManager, Page, Template, ComponentManager, Component,
TagManager, Tag, etc.
setUp() Method , Which is executed prior to each @Test method, define a common mock testing state
@BeforeEach
public void setUp() throws Exception {
aemContext.addModelsForClasses(SearchResultTest.class);
aemContext.load().json(MOCK_RESOURCE, PAGE_PATH );
}
• Add models at the package level – addModelsForClasses
• MOCK_RESOURCE Is the JSON file created Under class path - /src/test/resources
• @BeforeAll is used to signal that the annotated method should be executed before all tests in the current test class.
• @BeforeEach is used to signal that the annotated method should be executed before each tests in the current test class.
• @AfterAll, @AfterEach, @afterTestExecution, @postProcessTestInstance, @resolveParameter, @supportsParameter
• resource = aemContext.currentResource(PAGE_PATH); Set the aemContext to respective path and acquire page Object from It.
• Call the Sling Models class header= context.request().adaptTo(Header.class);
https://wcm.io/testing/aem-mock/junit5/apidocs/io/wcm/testing/mock/aem/junit5/AemContextExtension.html#afterAll-
org.junit.jupiter.api.extension.ExtensionContext-
• @Test The test annotation tells Junit that the public void method to which it is attached can be run as a test case. To run the method, Junit
first constructs a fresh instance of the class then invokes the annotated method. Any exceptions thrown by the test will be reported by Junit as
a failure. If no exceptions are thrown, the test is assumed to have succeeded.
• What is Junit Assert?
Assert is a method useful in determining Pass or Fail status of a test case, The assert methods are provided by the class
org.junit.Assert, assertions like Boolean, Null, Identical etc.
1.boolean conditions (true or false) : a) assertTrue(condition) b) assertFalse(condition)
2.Null object : a) assertNull(object) b) assertNotNull(object)
3.Identical : a) assertSame(expected, actual), It will return true if expected == actual
b) assertNotSame(expected, actual)
4. Assert Equals : assertEquals(expected, actual)
5. Assert Array Equals assertArrayEquals(expected, actual)
https://junit.org/junit5/docs/current/api/org.junit.jupiter.api/org/junit/jupiter/api/Assertions.html
@Test
public void testGetSfColor() throws Exception {
String msg = footer.getSfColor();
assertNotNull(msg);
assertEquals(msg, "--blue");
}
@Test
public void testGetIsEnabled() throws
Exception {
boolean msg = footer.isEnabled();
assertTrue(msg);
}
Multifield
@Test
Void testGetSecondry() {
aemContext.currentResource(“/component”);
header= aemContext.request().adaptTo(Header.class);
assertEquals(3, header.getSecondry().size());
assertEquals(“#”, header. getSecondry().get(0).get(“link”);
assertEquals(“COVID-19”, header. getSecondry().
get(0).get(“label”);
}
}
"secondary":{
"jcr:primaryType":"nt:unstructured",
"item0":{
"jcr:primaryType":"nt:unstructured",
"link":"#",
"label":"COVID-19"
},
"item1":{
"jcr:primaryType":"nt:unstructured",
"link":"#",
"label":"Depression"
},
"item2":{
"jcr:primaryType":"nt:unstructured",
"link":"#",
"label":"General health"
},
}
Returning Static value
Public String firstName() {
return “Unit-Testing”;
}
@Test
Void testFirstName() {
assertEquals(“Unit-Testing”, aemContext.registerService(new SearchResult()). firstName());
}
• What is mocking?
Mocking is a process used in unit testing when the unit being tested has external dependencies.
• org.mockito.junit.jupiter.MockitoExtension is a JUnit 5 extension provided by the Mockito library. It allows
library. It allows you to use the Mockito framework to create and inject mocked objects into your
JUnit 5 test classes.
In mocking, the dependencies are replaced by closely controlled replacements objects that simulate the
behavior of the real ones. There are three main possible types of replacement objects - fakes, stubs and mocks.
• Fakes: A Fake is an object that will replace the actual code by implementing the same interface but without interacting
with other objects.
• Stubs: A Stub is an object that will return a specific result based on a specific set of inputs and usually
won’t respond to anything outside of what is programed for the test.
• Mocks: A Mock is a much more sophisticated version of a Stub. It will still return values like a Stub, but it
like a Stub, but it can also be programmed with expectations in terms of how many times each method
should be called, in which order and with what data.
https://javadoc.io/doc/org.mockito/mockito-core/latest/org/mockito/Mockito.html
What is Mockito?
It internally uses the Java Reflection API to generate mock objects for a specific
interface. Mock objects are referred to as the dummy or proxy objects used for actual
implementations.
The main purpose of using the Mockito framework is to simplify the development of a test by
mocking external dependencies and use them in the test code.
• @Mock: It is used to mock the objects that helps in minimizing the repetitive mock objects. It
mock objects. It makes the test code and verification error easier to read as parameter names (field
names) are used to identify the mocks. The @Mock annotation is available in
the org.mockito package.
• when(...).thenReturn(...) − Mock implementation of get divide value method of calculated method.
calculated method.
• lenient().when().thenReturn()
"lenient()" method is useful today if you already leverage strict stubbing.
It is very useful because it drives cleaner tests and improved productivity.
@ExtendWith(MockitoExtension.class )
class SearchResultTest {
@Mock
private CalculateMethods calculateMethods;
@BeforeEach
public void setupMocks() {
Mockito.when(calculateMethods.divide(6, 3)).thenReturn(2.0);
}
@Test
public void testDivide() {
assertEquals(2.0, calculateMethods.divide(6, 3));
}
}
How to Mock @RequestAttribute value in Sling Model
@Model(adaptables = SlingHttpServletRequest.class,
defaultInjectionStrategy = DefaultInjectionStrategy.OPTIONAL)
public class ExampleSlingModel {
@RequestAttribute(name = "websitename")
private String websiteName;
@RequestAttribute
private int version;
@PostConstruct
public void init() {
websiteName = websiteName.concat(":websitename");
version = version * 2;
}
public String getWebsiteName() {
return websiteName;
}
public int getVersion() {
return version;
}
}
public class ExampleSlingModelTest {
@Rule
public final AemContext
aemContext = new AemContext(ResourceResolverType.JCR_MOCK);
private MockSlingHttpServletRequest request;
private ExampleSlingModel underTest;
@Before
public void setUp() throws Exception {
aemContext.addModelsForPackage("com.finning.platform.core.models.u
tils");
request = aemContext.request();
request.setAttribute("websitename", "sourcedcode");
request.setAttribute("version", 5);
}
@Test
public void test_getWebsiteName() {
underTest = request.adaptTo(ExampleSlingModel.class);
Assert.assertEquals("sourcedcode:websitename",
underTest.getWebsiteName());
}
@Test
public void test_getVersion() {
underTest = request.adaptTo(ExampleSlingModel.class);
Assert.assertEquals(10, underTest.getVersion());
} }
Important Links :
• https://junit.org/junit5/
• https://site.mockito.org/
• https://wcm.io/testing/
• https://sling.apache.org/documentation/development/sling-mock.html
References :
• https://experienceleague.adobe.com/docs/experience-manager-learn/getting-started-wknd-tutorial-
develop/project-archetype/unit-testing.html?lang=en
• https://aemsimplifiedbynikhil.wordpress.com/2021/04/19/getting-started-with-junit-code-coverage-
in-aem-using-mockito-framework/
• https://aem4beginner.blogspot.com/search/label/UNIT%20Testing
THANK YOU
Suman Sourav
iamsumansourav@gmail.com

More Related Content

Similar to Junit_.pptx

Unit testing php-unit - phing - selenium_v2
Unit testing   php-unit - phing - selenium_v2Unit testing   php-unit - phing - selenium_v2
Unit testing php-unit - phing - selenium_v2Tricode (part of Dept)
 
Industrial Strength Groovy - Tools for the Professional Groovy Developer: Pau...
Industrial Strength Groovy - Tools for the Professional Groovy Developer: Pau...Industrial Strength Groovy - Tools for the Professional Groovy Developer: Pau...
Industrial Strength Groovy - Tools for the Professional Groovy Developer: Pau...Paul King
 
Test Driven Development with PHPUnit
Test Driven Development with PHPUnitTest Driven Development with PHPUnit
Test Driven Development with PHPUnitMindfire Solutions
 
More on Fitnesse and Continuous Integration (Silicon Valley code camp 2012)
More on Fitnesse and Continuous Integration (Silicon Valley code camp 2012)More on Fitnesse and Continuous Integration (Silicon Valley code camp 2012)
More on Fitnesse and Continuous Integration (Silicon Valley code camp 2012)Jen Wong
 
Automated Unit Testing
Automated Unit TestingAutomated Unit Testing
Automated Unit TestingMike Lively
 
Junit and cactus
Junit and cactusJunit and cactus
Junit and cactusHimanshu
 
Bring the fun back to java
Bring the fun back to javaBring the fun back to java
Bring the fun back to javaciklum_ods
 
Javascript tdd byandreapaciolla
Javascript tdd byandreapaciollaJavascript tdd byandreapaciolla
Javascript tdd byandreapaciollaAndrea Paciolla
 
Testing your application on Google App Engine
Testing your application on Google App EngineTesting your application on Google App Engine
Testing your application on Google App EngineInphina Technologies
 
Testing Your Application On Google App Engine
Testing Your Application On Google App EngineTesting Your Application On Google App Engine
Testing Your Application On Google App EngineIndicThreads
 
Grails unit testing
Grails unit testingGrails unit testing
Grails unit testingpleeps
 
Improve unit tests with Mutants!
Improve unit tests with Mutants!Improve unit tests with Mutants!
Improve unit tests with Mutants!Paco van Beckhoven
 
比XML更好用的Java Annotation
比XML更好用的Java Annotation比XML更好用的Java Annotation
比XML更好用的Java Annotationjavatwo2011
 
Unit Testing on Android - Droidcon Berlin 2015
Unit Testing on Android - Droidcon Berlin 2015Unit Testing on Android - Droidcon Berlin 2015
Unit Testing on Android - Droidcon Berlin 2015Buşra Deniz, CSM
 
Testing the Enterprise Layers - the A, B, C's of Integration Testing - Aslak ...
Testing the Enterprise Layers - the A, B, C's of Integration Testing - Aslak ...Testing the Enterprise Layers - the A, B, C's of Integration Testing - Aslak ...
Testing the Enterprise Layers - the A, B, C's of Integration Testing - Aslak ...JAXLondon2014
 
Testing the Enterprise layers, with Arquillian
Testing the Enterprise layers, with ArquillianTesting the Enterprise layers, with Arquillian
Testing the Enterprise layers, with ArquillianVirtual JBoss User Group
 

Similar to Junit_.pptx (20)

Unit testing php-unit - phing - selenium_v2
Unit testing   php-unit - phing - selenium_v2Unit testing   php-unit - phing - selenium_v2
Unit testing php-unit - phing - selenium_v2
 
Industrial Strength Groovy - Tools for the Professional Groovy Developer: Pau...
Industrial Strength Groovy - Tools for the Professional Groovy Developer: Pau...Industrial Strength Groovy - Tools for the Professional Groovy Developer: Pau...
Industrial Strength Groovy - Tools for the Professional Groovy Developer: Pau...
 
Introduction to JUnit
Introduction to JUnitIntroduction to JUnit
Introduction to JUnit
 
Test Driven Development with PHPUnit
Test Driven Development with PHPUnitTest Driven Development with PHPUnit
Test Driven Development with PHPUnit
 
More on Fitnesse and Continuous Integration (Silicon Valley code camp 2012)
More on Fitnesse and Continuous Integration (Silicon Valley code camp 2012)More on Fitnesse and Continuous Integration (Silicon Valley code camp 2012)
More on Fitnesse and Continuous Integration (Silicon Valley code camp 2012)
 
Automated Unit Testing
Automated Unit TestingAutomated Unit Testing
Automated Unit Testing
 
Good Practices On Test Automation
Good Practices On Test AutomationGood Practices On Test Automation
Good Practices On Test Automation
 
Junit and cactus
Junit and cactusJunit and cactus
Junit and cactus
 
Bring the fun back to java
Bring the fun back to javaBring the fun back to java
Bring the fun back to java
 
Javascript tdd byandreapaciolla
Javascript tdd byandreapaciollaJavascript tdd byandreapaciolla
Javascript tdd byandreapaciolla
 
Testing your application on Google App Engine
Testing your application on Google App EngineTesting your application on Google App Engine
Testing your application on Google App Engine
 
Testing Your Application On Google App Engine
Testing Your Application On Google App EngineTesting Your Application On Google App Engine
Testing Your Application On Google App Engine
 
ikp321-04
ikp321-04ikp321-04
ikp321-04
 
Grails unit testing
Grails unit testingGrails unit testing
Grails unit testing
 
Improve unit tests with Mutants!
Improve unit tests with Mutants!Improve unit tests with Mutants!
Improve unit tests with Mutants!
 
比XML更好用的Java Annotation
比XML更好用的Java Annotation比XML更好用的Java Annotation
比XML更好用的Java Annotation
 
Unit Testing on Android - Droidcon Berlin 2015
Unit Testing on Android - Droidcon Berlin 2015Unit Testing on Android - Droidcon Berlin 2015
Unit Testing on Android - Droidcon Berlin 2015
 
Junit and testNG
Junit and testNGJunit and testNG
Junit and testNG
 
Testing the Enterprise Layers - the A, B, C's of Integration Testing - Aslak ...
Testing the Enterprise Layers - the A, B, C's of Integration Testing - Aslak ...Testing the Enterprise Layers - the A, B, C's of Integration Testing - Aslak ...
Testing the Enterprise Layers - the A, B, C's of Integration Testing - Aslak ...
 
Testing the Enterprise layers, with Arquillian
Testing the Enterprise layers, with ArquillianTesting the Enterprise layers, with Arquillian
Testing the Enterprise layers, with Arquillian
 

Recently uploaded

+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...Health
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyviewmasabamasaba
 
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...Bert Jan Schrijver
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnAmarnathKambale
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...masabamasaba
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfonteinmasabamasaba
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesVictorSzoltysek
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrandmasabamasaba
 
Architecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastArchitecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastPapp Krisztián
 
Define the academic and professional writing..pdf
Define the academic and professional writing..pdfDefine the academic and professional writing..pdf
Define the academic and professional writing..pdfPearlKirahMaeRagusta1
 
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...Jittipong Loespradit
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️Delhi Call girls
 
WSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go PlatformlessWSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go PlatformlessWSO2
 
Harnessing ChatGPT - Elevating Productivity in Today's Agile Environment
Harnessing ChatGPT  - Elevating Productivity in Today's Agile EnvironmentHarnessing ChatGPT  - Elevating Productivity in Today's Agile Environment
Harnessing ChatGPT - Elevating Productivity in Today's Agile EnvironmentVictorSzoltysek
 
Announcing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareAnnouncing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareJim McKeeth
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech studentsHimanshiGarg82
 
WSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With SimplicityWSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With SimplicityWSO2
 

Recently uploaded (20)

+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
 
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand
 
Architecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastArchitecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the past
 
Define the academic and professional writing..pdf
Define the academic and professional writing..pdfDefine the academic and professional writing..pdf
Define the academic and professional writing..pdf
 
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
WSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go PlatformlessWSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go Platformless
 
Harnessing ChatGPT - Elevating Productivity in Today's Agile Environment
Harnessing ChatGPT  - Elevating Productivity in Today's Agile EnvironmentHarnessing ChatGPT  - Elevating Productivity in Today's Agile Environment
Harnessing ChatGPT - Elevating Productivity in Today's Agile Environment
 
Announcing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareAnnouncing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK Software
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students
 
WSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With SimplicityWSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
 

Junit_.pptx

  • 2. AGENDA Introduction Set Up JUnit Testing The Anatomy of a JUnit
  • 3. INTRODUCTION • JUnit is the most popular Java unit testing framework. An open-source framework, it’s used to write and run repeatable automated tests.
  • 4. WHY UNIT TESTING ? Unit Test cases are mandatory this days you cannot deploy your code using Cloud Manager until you have 50% of code coverage. • JUnit 5 = JUnit Platform + JUnit Jupiter + JUnit Vintage • Mockito Testing Framework • wcm.io Test Framework • Apache Sling Mocks https://experienceleague.adobe.com/docs/experience-manager-learn/getting-started-wknd-tutorial- develop/project-archetype/unit-testing.html?lang=en
  • 5. SET UP JUNIT TESTING Create Java file(AbcTest.java) under core/src/test/java/com/verily/core/models/AbcTest.java Create Json File(Abc.json) under core/src/test/resources/ com/verily/core/Abc.json To get JSON File http://localhost:4502/content/verily/us/..../searchresult.infinity.json Generally, The testcase class name starts or ends with Test word and all test methods generally begins with “test” word. Matching expected result with actual result.
  • 6. THE ANATOMY OF A JUNIT
  • 7. @ExtendWith(AemContextExtension.class) class EventTest { private final AemContext aemContext = new AemContext(); private EventTest event; @BeforeEach void setUp() { aemContext.addModelsForClasses(Event.class); aemContext.load().json("/com/mySite/core/models/about.json", "/component"); Resource resource = aemContext.currentResource("/component/event"); event=aemContext.request().adaptTo(Event.class); } @Test void testGetEmail() { final String expected = "abc@gmail.com"; assertEquals(expected, event.getEmail()); } @Test void testGetAddress() { final String expected = "India"; assertEquals(expected, event.getAddress()); } } { "event": { "email":"abc@gmail.com", "address": "india" } }
  • 8. Setting up AEM test context : import org.junit.jupiter.api.extension.ExtendWith; import io.wcm.testing.mock.aem.junit5.AemContext; import io.wcm.testing.mock.aem.junit5.AemContextExtension; ... @ExtendWith(AemContextExtension.class) class SearchResultTest { private final AemContext aemContext = new AemContext(); private String MOCK_RESOURCE = "/com/verily/core/models/SearchResult.json"; private String PAGE_PATH = "/content/verily/us/en"; • AemContextExtension context can be injected into a Junit test using a custom Junit Extension named AemContextExtension. • The SearchResultTest Sling Model is registered into this context • Mock JCR content structures are created in this context • Custom OSGi services can be registered in this context • Provides various common required mock objects and helpers such as SlingHttpServletRequest objects, various mock Sling and AEM OSGi services such as ModelFactory, PageManager, Page, Template, ComponentManager, Component, TagManager, Tag, etc.
  • 9. setUp() Method , Which is executed prior to each @Test method, define a common mock testing state @BeforeEach public void setUp() throws Exception { aemContext.addModelsForClasses(SearchResultTest.class); aemContext.load().json(MOCK_RESOURCE, PAGE_PATH ); } • Add models at the package level – addModelsForClasses • MOCK_RESOURCE Is the JSON file created Under class path - /src/test/resources • @BeforeAll is used to signal that the annotated method should be executed before all tests in the current test class. • @BeforeEach is used to signal that the annotated method should be executed before each tests in the current test class. • @AfterAll, @AfterEach, @afterTestExecution, @postProcessTestInstance, @resolveParameter, @supportsParameter • resource = aemContext.currentResource(PAGE_PATH); Set the aemContext to respective path and acquire page Object from It. • Call the Sling Models class header= context.request().adaptTo(Header.class); https://wcm.io/testing/aem-mock/junit5/apidocs/io/wcm/testing/mock/aem/junit5/AemContextExtension.html#afterAll- org.junit.jupiter.api.extension.ExtensionContext-
  • 10. • @Test The test annotation tells Junit that the public void method to which it is attached can be run as a test case. To run the method, Junit first constructs a fresh instance of the class then invokes the annotated method. Any exceptions thrown by the test will be reported by Junit as a failure. If no exceptions are thrown, the test is assumed to have succeeded. • What is Junit Assert? Assert is a method useful in determining Pass or Fail status of a test case, The assert methods are provided by the class org.junit.Assert, assertions like Boolean, Null, Identical etc. 1.boolean conditions (true or false) : a) assertTrue(condition) b) assertFalse(condition) 2.Null object : a) assertNull(object) b) assertNotNull(object) 3.Identical : a) assertSame(expected, actual), It will return true if expected == actual b) assertNotSame(expected, actual) 4. Assert Equals : assertEquals(expected, actual) 5. Assert Array Equals assertArrayEquals(expected, actual) https://junit.org/junit5/docs/current/api/org.junit.jupiter.api/org/junit/jupiter/api/Assertions.html @Test public void testGetSfColor() throws Exception { String msg = footer.getSfColor(); assertNotNull(msg); assertEquals(msg, "--blue"); } @Test public void testGetIsEnabled() throws Exception { boolean msg = footer.isEnabled(); assertTrue(msg); }
  • 11. Multifield @Test Void testGetSecondry() { aemContext.currentResource(“/component”); header= aemContext.request().adaptTo(Header.class); assertEquals(3, header.getSecondry().size()); assertEquals(“#”, header. getSecondry().get(0).get(“link”); assertEquals(“COVID-19”, header. getSecondry(). get(0).get(“label”); } } "secondary":{ "jcr:primaryType":"nt:unstructured", "item0":{ "jcr:primaryType":"nt:unstructured", "link":"#", "label":"COVID-19" }, "item1":{ "jcr:primaryType":"nt:unstructured", "link":"#", "label":"Depression" }, "item2":{ "jcr:primaryType":"nt:unstructured", "link":"#", "label":"General health" }, }
  • 12. Returning Static value Public String firstName() { return “Unit-Testing”; } @Test Void testFirstName() { assertEquals(“Unit-Testing”, aemContext.registerService(new SearchResult()). firstName()); }
  • 13. • What is mocking? Mocking is a process used in unit testing when the unit being tested has external dependencies. • org.mockito.junit.jupiter.MockitoExtension is a JUnit 5 extension provided by the Mockito library. It allows library. It allows you to use the Mockito framework to create and inject mocked objects into your JUnit 5 test classes. In mocking, the dependencies are replaced by closely controlled replacements objects that simulate the behavior of the real ones. There are three main possible types of replacement objects - fakes, stubs and mocks. • Fakes: A Fake is an object that will replace the actual code by implementing the same interface but without interacting with other objects. • Stubs: A Stub is an object that will return a specific result based on a specific set of inputs and usually won’t respond to anything outside of what is programed for the test. • Mocks: A Mock is a much more sophisticated version of a Stub. It will still return values like a Stub, but it like a Stub, but it can also be programmed with expectations in terms of how many times each method should be called, in which order and with what data. https://javadoc.io/doc/org.mockito/mockito-core/latest/org/mockito/Mockito.html
  • 14. What is Mockito? It internally uses the Java Reflection API to generate mock objects for a specific interface. Mock objects are referred to as the dummy or proxy objects used for actual implementations. The main purpose of using the Mockito framework is to simplify the development of a test by mocking external dependencies and use them in the test code. • @Mock: It is used to mock the objects that helps in minimizing the repetitive mock objects. It mock objects. It makes the test code and verification error easier to read as parameter names (field names) are used to identify the mocks. The @Mock annotation is available in the org.mockito package. • when(...).thenReturn(...) − Mock implementation of get divide value method of calculated method. calculated method. • lenient().when().thenReturn() "lenient()" method is useful today if you already leverage strict stubbing. It is very useful because it drives cleaner tests and improved productivity.
  • 15. @ExtendWith(MockitoExtension.class ) class SearchResultTest { @Mock private CalculateMethods calculateMethods; @BeforeEach public void setupMocks() { Mockito.when(calculateMethods.divide(6, 3)).thenReturn(2.0); } @Test public void testDivide() { assertEquals(2.0, calculateMethods.divide(6, 3)); } }
  • 16. How to Mock @RequestAttribute value in Sling Model @Model(adaptables = SlingHttpServletRequest.class, defaultInjectionStrategy = DefaultInjectionStrategy.OPTIONAL) public class ExampleSlingModel { @RequestAttribute(name = "websitename") private String websiteName; @RequestAttribute private int version; @PostConstruct public void init() { websiteName = websiteName.concat(":websitename"); version = version * 2; } public String getWebsiteName() { return websiteName; } public int getVersion() { return version; } } public class ExampleSlingModelTest { @Rule public final AemContext aemContext = new AemContext(ResourceResolverType.JCR_MOCK); private MockSlingHttpServletRequest request; private ExampleSlingModel underTest; @Before public void setUp() throws Exception { aemContext.addModelsForPackage("com.finning.platform.core.models.u tils"); request = aemContext.request(); request.setAttribute("websitename", "sourcedcode"); request.setAttribute("version", 5); } @Test public void test_getWebsiteName() { underTest = request.adaptTo(ExampleSlingModel.class); Assert.assertEquals("sourcedcode:websitename", underTest.getWebsiteName()); } @Test public void test_getVersion() { underTest = request.adaptTo(ExampleSlingModel.class); Assert.assertEquals(10, underTest.getVersion()); } }
  • 17. Important Links : • https://junit.org/junit5/ • https://site.mockito.org/ • https://wcm.io/testing/ • https://sling.apache.org/documentation/development/sling-mock.html References : • https://experienceleague.adobe.com/docs/experience-manager-learn/getting-started-wknd-tutorial- develop/project-archetype/unit-testing.html?lang=en • https://aemsimplifiedbynikhil.wordpress.com/2021/04/19/getting-started-with-junit-code-coverage- in-aem-using-mockito-framework/ • https://aem4beginner.blogspot.com/search/label/UNIT%20Testing