SlideShare una empresa de Scribd logo
1 de 26
JUnit Functional test cases
Abstract
• The main motto of this white paper is what
the issues to write test cases using JUnit are
and how to overcome those issues.
Table of Contents
• ABSTRACT
1. INTRODUCTION
2. PROBLEM STATEMENT
3. SOLUTION
4. BENEFITS
5. CONCLUSION
6. REFERENCES
7. ABOUT THE AUTHOR
8. ABOUT WHISHWORKS
Introduction
• We have multiple unit test frameworks to
write unit and functional test cases for our
services. When we write functional test cases
using JUnit we can’t mock mule components.
To resolve this issues we have to use MUnit
and I am going to explain what is the problem
with JUnit and how to resolve using MUnit in
the below.
Problem Statement
• When we write functional test cases using JUnit, the test case will
directly connect to original components like SAP, Salesforce etc. and
insert/select the data. It is the issue in JUnit functional test case
why because we are writing functional test cases to check whether
entire functionality is working as expected or not without modifying
the original components(SAP,Salesforce,Database) data, but in JUnit
functional test cases it is directly connecting to original components
and modifying the original data.
• Examples:
1. SAP Connector
• Mule flow:
• Flow of execution
1. Trigger the service with xml request.
2. Receive the input request and process it.
3. Transform the processed request to SAP IDoc
and push it to SAP.
• Functional test case using JUnit:
• Public void functionalTest(){
•
• File fXmlFile = new File(request.xml);
• StringBuilder sb = new StringBuilder();
• BufferedReader br = new BufferedReader(new FileReader(fXmlFile));
•
• String sCurrentLine = new String();
• //Read the data from file and append to string
• while ((sCurrentLine = br.readLine()) != null) {
• sb.append(sCurrentLine);
• }
•
• DefaultHttpClient httpclient = new DefaultHttpClient();
•
• HttpPost httppost = new HttpPost(requrl);
•
• httppost.setEntity(new StringEntity(sb.toString(), "UTF-8"));
• //Trigger the service
• HttpResponse response = httpclient.execute(httppost);
•
• ----
• ----
• }
•
• Flow of execution
1. Read the input request from request.xml file.
2. Trigger the service with above request.
3. Process the input request.
4. Transform the processed request to SAP IDoc
and push it to SAP.
• Issue
• Here we are unable to mock the SAP
component so the test case is directly pushing
the IDoc to original SAP.
• NOTE: Not only pushing the IDoc to SAP, at the
time of receiving IDoc from SAP also we will
• 2. Salesforce
• Mule flow
• Flow of execution
1. Trigger the service with xml request.
2. Processes the input request.
3. Create the processed request as customer in
Salesforce.
• Functional Test Case
• Public void functionalTest(){
•
• File fXmlFile = new File(request.xml);
• StringBuilder sb = new StringBuilder();
• BufferedReader br = new BufferedReader(new FileReader(fXmlFile));
•
• String sCurrentLine = new String();
• // Read the data from file and append to string
• while ((sCurrentLine = br.readLine()) != null) {
• sb.append(sCurrentLine);
• }
•
• DefaultHttpClient httpclient = new DefaultHttpClient();
•
• HttpPost httppost = new HttpPost(requrl);
•
• httppost.setEntity(new StringEntity(sb.toString(), "UTF-8"));
• //Trigger the service
• HttpResponse response = httpclient.execute(httppost);
•
• ----
• ----
• }
• Flow of Execution
1. First read the input request from request.xml
file.
2. Trigger the service with above request.
3. Process the input request.
4. Create the customer in salesforce.
• Issue
• Here also we are unable to mock the
Salesforce component so it will connect to
original Salesforce connector and create the
Solution
• To resolve the above JUnit functional test case
issue we have a separate framework called
MUnit. MUnit is also one framework which is
used to write test cases as same as JUnit, but
here in MUnit we can mock all components
like SAP, Salesforce, Database etc. So to
overcome the above problem we can use
MUnit to write functional test cases.
• Example
• Mocking Salesforce test case using Munit
• .mflow
• <?xml version="1.0" encoding="UTF-8"?>
•
• <mule xmlns="http://www.mulesoft.org/schema/mule/core" xmlns:vm="http://www.mulesoft.org/schema/mule/vm"
xmlns:sfdc="http://www.mulesoft.org/schema/mule/sfdc" xmlns:doc="http://www.mulesoft.org/schema/mule/documentation"
xmlns:spring="http://www.springframework.org/schema/beans" xmlns:core="http://www.mulesoft.org/schema/mule/core" version="EE-3.4.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.mulesoft.org/schema/mule/vm
http://www.mulesoft.org/schema/mule/vm/current/mule-vm.xsd
• http://www.mulesoft.org/schema/mule/sfdc http://www.mulesoft.org/schema/mule/sfdc/5.0/mule-sfdc.xsd
• http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-current.xsd
• http://www.mulesoft.org/schema/mule/core http://www.mulesoft.org/schema/mule/core/current/mule.xsd">
• <vm:endpoint exchange-pattern="request-response" path="CREATE_CSTMR_VM" name="CREATE_CSTMR_VM" doc:name="VM"/>
• <vm:endpoint exchange-pattern="request-response" path="INSERT_PERSON_ACT_VM" name="INSERT_PERSON_ACT_VM" doc:name="VM"/>
• <flow name="CreateCustomerSFServiceTSFlow1" doc:name="CreateCustomerSFServiceTSFlow1">
• <vm:inbound-endpoint exchange-pattern="request-response" ref="CREATE_CSTMR_VM" doc:name="VM"/>
• <component class="com.vertu.services.ecom.maintaincustmr.processor.CreateCustomerProcessor" doc:name="CreateCustomerProcessor"/>
• </flow>
• <flow name="CreateCustomerSFServiceTSFlow2" doc:name="CreateCustomerSFServiceTSFlow2">
• <vm:inbound-endpoint exchange-pattern="request-response" ref="INSERT_PERSON_ACT_VM" doc:name="VM"/>
• <sfdc:create config-ref="ECOM_SALESFORCE_CONNECTOR" type="#[payload.Type]" doc:name="Salesforce">
• <sfdc:objects ref="#[payload.Object]"/>
• </sfdc:create>
• </flow>
• </mule>
• Here we have a Salesforce component to create the customer in Salesforce and return the customer-id as payload. So in functional test case we
should mock this component without connecting to original Salesforce.
• How to mock Salesforce component in MUnit functional test case
•
• To mock Salesforce component, first we should know
•
• Endpoint type.
• Name of the message processor and namespace of endpoint (from auto-generated
XML).
• The type of payload the endpoint returns.
•
•
• Mocking above flow Salesforce component
•
• Create the salesforce response payload.
•
• List<Map<String,Object>> l1 = new ArrayList<Map<String,Object>>();
• Map<String,Object> m1 = new HashMap<Srtring,Object>>();
• m1.put(“custid”,”1234”);
• l1.add(m1);
•
• Mock the salesforce component and return the above created list as response
payload.
•
• whenMessageProcessor("create").ofNamespace("sfdc").
• MUnit functional test case for above flow
• public class MUnitSalesforceStubTest extends FunctionalMunitSuite {
• /**
• * The purpose of this method is to define the list of flow
• * files which will be loaded by Munit test case before executing
• * Munit test case. Specify multiple flow files as comma
• * separated XML files.
• */
• @Override
• protected String getConfigResources() {
• return "src/main/app/MUnitSFTest.xml";
• }
• /**
• *The purpose of this method is to define the list of
• flow name which will execute in Munit test case.
• */
• protected List<String> getFlowsExcludedOfInboundDisabling(){
• List<String> list = new ArrayList<String>();
• list.add("CreateCustomerSFServiceTSFlow2");
• return list;
• }
• /**
• * The purpose of this method is to flip between mock
• * and real time interfaces. Return false to Mock
• * all endpoints in your flow
• */
• @Override
• public boolean haveToMockMuleConnectors() {
• return true;
• }
• /**
• * Java based Munit test case. Contains mocking and
• * invocation of flows and assertions.
• */
• @Test
• public void validateEchoFlow() throws Exception {
•
• List<Map<String,Object>> l1 = new ArrayList<Map<String,Object>>();
• Map<String,Object> m1 = new HashMap<Srtring,Object>>();
• m1.put(“custid”,”1234”);
• l1.add(m1);
•
• // Mock SFDC outbound endpoint
• whenMessageProcessor("query").ofNamespace("sfdc").thenReturn( muleMessageWithPayload( l1)
);
•
• // Run the Munit test case by passing a test payload
• MuleEvent resultEvent = runFlow( " CreateCustomerSFServiceTSFlow1", testEvent(“request”));
• // The resultEvent contains response from the VM flow
• System.out.println( "The flow response is:: " + resultEvent.getMessage().getPayloadAsString() );
• // Do any assertion here using Assert.equals() for asserting response // payload
• }
• }
• Mocking Database component test case using MUnit
• .mflow
<flow name="CheckAcctIDFlow" doc:name="CheckAcctIDFlow">
<vm:inbound-endpoint exchange-pattern="request-response"
ref="FETCH_ACT_GUID_VM1" doc:name="FETCH_ACT_GUID_VM1"/>
<logger message="#[message.inboundProperties['ACCT_GUID']]"
level="INFO" doc:name="Logger"/>
<jdbc-ee:outbound-endpoint exchange-pattern="request-
response" queryKey="Get_ACC_ID" queryTimeout="-1" connector-
ref="CDMR_JDBC_CONNECTOR" doc:name="Get_ACCT_ID"/>
</flow>
• Here we have a database component used to select and return the
account-id from database. So we need to mock this component in
functional test case.
• Mocking above flow Database component
•
• Create the database response payload.
•
• List<Map<String,Object>> l1 = new
ArrayList<Map<String,Object>>();
• Map<String,Object> m1 = new
HashMap<Srtring,Object>>();
• m1.put(“accountid”,”1234”);
• l1.add(m1);
•
• Mock the database component and return the above
created list as response payload.
•
• whenEndpointWithAddress( "jdbc://Get_ACC_ID"
).thenReturn(new DefaultMuleMessage(l1,
• MUnit functional test case for above flow
• public class MUnitSalesforceStubTest extends FunctionalMunitSuite {
• /**
• * The purpose of this method is to define the list of flow
• * files which will be loaded by Munit test case before executing
• * Munit test case. Specify multiple flow files as comma
• * separated XML files.
• */
• @Override
• protected String getConfigResources() {
• return "src/main/app/MUnitSFTest.xml";
• }
•
• /**
• * The purpose of this method is to flip between mock
• * and real time interfaces. Return false to Mock
• * all endpoints in your flow
• */
• @Override
• public boolean haveToMockMuleConnectors() {
• return true;
• }
• /**
• * Java based Munit test case. Contains mocking and
• * invocation of flows and assertions.
• */
• @Test
• public void validateEchoFlow() throws Exception {
•
• List<Map<String,Object>> l1 = new ArrayList<Map<String,Object>>();
• Map<String,Object> m1 = new HashMap<Srtring,Object>>();
• m1.put(“accountid”,”1234”);
• l1.add(m1);
• // Mock Database outbound endpoint
• whenEndpointWithAddress( "jdbc://Get_ACC_ID"
).thenReturn(new DefaultMuleMessage(l1,
muleContext ) );
•
• // Run the Munit test case by passing a test payload
• MuleEvent resultEvent = runFlow( " CheckAcctIDFlow ",
testEvent(“request”));
• // The resultEvent contains response from the VM flow
• System.out.println( "The flow response is:: " +
resultEvent.getMessage().getPayloadAsString() );
• // Do any assertion here using Assert.equals() for
asserting response // payload
• }
• }
Benefits
• Create Java based or Mule flow based unit test cases
• Mock endpoints (Salesforce, Database, or SAP etc.) to
return custom payloads for unit testing
• Dynamically flip/parameterize Munit test cases to Mock
payloads or use real time interfaces
• Support functional unit testing similar to Mule Functional
test case
• Support Assertion through Spy processors and additionally
verify flows using Message verifiers (introspect payload at
different flows for flow navigation)
• Support Asynchronous flow processing and request-
response processors
• Mock without custom database or in memory database
• Automate test cases using Maven and generate HTML
reports using Surefire plugins
Conclusion
• When we write test cases using JUnit we can’t
mock all mule components and the test case
will connect to original connectors(SAP,
Salesforce). So to overcome this issue we can
use MUnit to write test cases effectively.
References
• https://github.com/mulesoft/munit
• http://www.mulesoft.org/documentation/dis
play/EARLYACCESS/MUnit
• http://java.dzone.com/articles/mule-best-
practices-backed

Más contenido relacionado

La actualidad más candente

La actualidad más candente (12)

Passing java arrays in oracle stored procedure from mule esb flow
Passing java arrays in oracle stored procedure from mule esb flowPassing java arrays in oracle stored procedure from mule esb flow
Passing java arrays in oracle stored procedure from mule esb flow
 
Mule new jdbc component
Mule new jdbc componentMule new jdbc component
Mule new jdbc component
 
Mule esb :Data Weave
Mule esb :Data WeaveMule esb :Data Weave
Mule esb :Data Weave
 
Send email attachment using smtp in mule esb
Send email attachment using smtp in mule esbSend email attachment using smtp in mule esb
Send email attachment using smtp in mule esb
 
Groovy example in mule
Groovy example in muleGroovy example in mule
Groovy example in mule
 
Mule jdbc
Mule   jdbcMule   jdbc
Mule jdbc
 
Vm component in mule
Vm component in muleVm component in mule
Vm component in mule
 
MuleSoft ESB - CSV File to Database
MuleSoft ESB - CSV File to DatabaseMuleSoft ESB - CSV File to Database
MuleSoft ESB - CSV File to Database
 
Mule dataweave
Mule dataweaveMule dataweave
Mule dataweave
 
Mule overview
Mule overviewMule overview
Mule overview
 
Mule Ajax Connector
Mule Ajax ConnectorMule Ajax Connector
Mule Ajax Connector
 
Mule esb
Mule esbMule esb
Mule esb
 

Destacado

Destacado (20)

Mule security saml
Mule security samlMule security saml
Mule security saml
 
Dataweave 160103180124
Dataweave 160103180124Dataweave 160103180124
Dataweave 160103180124
 
Mule esb soap_service
Mule esb soap_serviceMule esb soap_service
Mule esb soap_service
 
File component in mule
File component in muleFile component in mule
File component in mule
 
Mule for each scope headerc ollection
Mule for each scope headerc ollectionMule for each scope headerc ollection
Mule for each scope headerc ollection
 
Choice component in mule
Choice component in mule Choice component in mule
Choice component in mule
 
Anypoint data gateway
Anypoint data gatewayAnypoint data gateway
Anypoint data gateway
 
Filter expression in mule
Filter expression in muleFilter expression in mule
Filter expression in mule
 
Mule esb
Mule esbMule esb
Mule esb
 
Mule soap
Mule soapMule soap
Mule soap
 
Mule management console installation
Mule management console installation Mule management console installation
Mule management console installation
 
Anypoint data gateway
Anypoint data gatewayAnypoint data gateway
Anypoint data gateway
 
Mule database-connectors
Mule database-connectorsMule database-connectors
Mule database-connectors
 
Junit in mule
Junit in muleJunit in mule
Junit in mule
 
Commit a project in svn using svn plugin in anypoint studio
Commit a project in svn using svn plugin in anypoint studioCommit a project in svn using svn plugin in anypoint studio
Commit a project in svn using svn plugin in anypoint studio
 
Mule integration with linkedin
Mule integration with linkedinMule integration with linkedin
Mule integration with linkedin
 
Expression filter in Mule
Expression filter in MuleExpression filter in Mule
Expression filter in Mule
 
.Net architecture with mule soft
.Net architecture with mule soft.Net architecture with mule soft
.Net architecture with mule soft
 
How to commit a project in svn using svn plugin in anypointstudio
How to commit a project in svn using svn plugin in anypointstudioHow to commit a project in svn using svn plugin in anypointstudio
How to commit a project in svn using svn plugin in anypointstudio
 
Send email attachment using smtp in mule esb
Send email attachment using smtp  in mule esbSend email attachment using smtp  in mule esb
Send email attachment using smtp in mule esb
 

Similar a Junit in mule demo

Project FoX: A Tool That Offers Automated Testing Using a Formal Approach
Project FoX: A Tool That Offers Automated Testing Using a Formal ApproachProject FoX: A Tool That Offers Automated Testing Using a Formal Approach
Project FoX: A Tool That Offers Automated Testing Using a Formal Approach
Ivo Neskovic
 
Ive posted 3 classes after the instruction that were given at star.pdf
Ive posted 3 classes after the instruction that were given at star.pdfIve posted 3 classes after the instruction that were given at star.pdf
Ive posted 3 classes after the instruction that were given at star.pdf
deepaarora22
 

Similar a Junit in mule demo (20)

J unit
J unitJ unit
J unit
 
Junit in mule demo
Junit in mule demoJunit in mule demo
Junit in mule demo
 
Munit junit test case
Munit junit test caseMunit junit test case
Munit junit test case
 
Mocking with salesforce using Munit
Mocking with salesforce using MunitMocking with salesforce using Munit
Mocking with salesforce using Munit
 
Spring batch
Spring batchSpring batch
Spring batch
 
JavaScript for real men
JavaScript for real menJavaScript for real men
JavaScript for real men
 
Project FoX: A Tool That Offers Automated Testing Using a Formal Approach
Project FoX: A Tool That Offers Automated Testing Using a Formal ApproachProject FoX: A Tool That Offers Automated Testing Using a Formal Approach
Project FoX: A Tool That Offers Automated Testing Using a Formal Approach
 
Javascript
JavascriptJavascript
Javascript
 
Test driven development
Test driven developmentTest driven development
Test driven development
 
Salesforce asynchronous apex
Salesforce asynchronous apexSalesforce asynchronous apex
Salesforce asynchronous apex
 
Introduction to C ++.pptx
Introduction to C ++.pptxIntroduction to C ++.pptx
Introduction to C ++.pptx
 
Performance Tuning and Optimization
Performance Tuning and OptimizationPerformance Tuning and Optimization
Performance Tuning and Optimization
 
Unit Testing
Unit TestingUnit Testing
Unit Testing
 
How to use batch component
How to use batch componentHow to use batch component
How to use batch component
 
BITM3730 10-3.pptx
BITM3730 10-3.pptxBITM3730 10-3.pptx
BITM3730 10-3.pptx
 
Rdbms chapter 1 function
Rdbms chapter 1 functionRdbms chapter 1 function
Rdbms chapter 1 function
 
BITM3730 10-4.pptx
BITM3730 10-4.pptxBITM3730 10-4.pptx
BITM3730 10-4.pptx
 
PHP - Introduction to PHP Date and Time Functions
PHP -  Introduction to  PHP Date and Time FunctionsPHP -  Introduction to  PHP Date and Time Functions
PHP - Introduction to PHP Date and Time Functions
 
ServiceNow Knowledge11 Advanced Scripting & Debugging Lab
ServiceNow Knowledge11 Advanced Scripting & Debugging LabServiceNow Knowledge11 Advanced Scripting & Debugging Lab
ServiceNow Knowledge11 Advanced Scripting & Debugging Lab
 
Ive posted 3 classes after the instruction that were given at star.pdf
Ive posted 3 classes after the instruction that were given at star.pdfIve posted 3 classes after the instruction that were given at star.pdf
Ive posted 3 classes after the instruction that were given at star.pdf
 

Más de javeed_mhd

Más de javeed_mhd (20)

For each component in mule
For each component in muleFor each component in mule
For each component in mule
 
Filter expression in mule
Filter expression in muleFilter expression in mule
Filter expression in mule
 
Database component in mule
Database component in muleDatabase component in mule
Database component in mule
 
Choice component in mule
Choice component in muleChoice component in mule
Choice component in mule
 
Mule management console installation
Mule management console installation Mule management console installation
Mule management console installation
 
Mule esb made system integration easy
Mule esb made system integration easy Mule esb made system integration easy
Mule esb made system integration easy
 
Message properties component in mule
Message properties component in muleMessage properties component in mule
Message properties component in mule
 
How to install sonarqube plugin in anypoint
How to install sonarqube plugin in anypoint How to install sonarqube plugin in anypoint
How to install sonarqube plugin in anypoint
 
Mapping and listing with mule
Mapping and listing with mule Mapping and listing with mule
Mapping and listing with mule
 
Mule any point exchange
Mule any point exchangeMule any point exchange
Mule any point exchange
 
Mule esb api layer
Mule esb api layer Mule esb api layer
Mule esb api layer
 
Mule Maven Plugin
Mule Maven PluginMule Maven Plugin
Mule Maven Plugin
 
Mule esb stripe
Mule esb stripeMule esb stripe
Mule esb stripe
 
Mule with stored procedure
Mule with stored procedureMule with stored procedure
Mule with stored procedure
 
Deploying and running in mule standalone
Deploying and running in mule standaloneDeploying and running in mule standalone
Deploying and running in mule standalone
 
Presentation
PresentationPresentation
Presentation
 
Scatter gather in mule
Scatter gather in muleScatter gather in mule
Scatter gather in mule
 
Xml to xml transformation in mule
Xml to xml transformation in muleXml to xml transformation in mule
Xml to xml transformation in mule
 
Maven
MavenMaven
Maven
 
Java programming course for beginners
Java programming course for beginnersJava programming course for beginners
Java programming course for beginners
 

Último

Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 

Último (20)

Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 

Junit in mule demo

  • 2. Abstract • The main motto of this white paper is what the issues to write test cases using JUnit are and how to overcome those issues.
  • 3. Table of Contents • ABSTRACT 1. INTRODUCTION 2. PROBLEM STATEMENT 3. SOLUTION 4. BENEFITS 5. CONCLUSION 6. REFERENCES 7. ABOUT THE AUTHOR 8. ABOUT WHISHWORKS
  • 4. Introduction • We have multiple unit test frameworks to write unit and functional test cases for our services. When we write functional test cases using JUnit we can’t mock mule components. To resolve this issues we have to use MUnit and I am going to explain what is the problem with JUnit and how to resolve using MUnit in the below.
  • 5. Problem Statement • When we write functional test cases using JUnit, the test case will directly connect to original components like SAP, Salesforce etc. and insert/select the data. It is the issue in JUnit functional test case why because we are writing functional test cases to check whether entire functionality is working as expected or not without modifying the original components(SAP,Salesforce,Database) data, but in JUnit functional test cases it is directly connecting to original components and modifying the original data. • Examples: 1. SAP Connector • Mule flow:
  • 6.
  • 7. • Flow of execution 1. Trigger the service with xml request. 2. Receive the input request and process it. 3. Transform the processed request to SAP IDoc and push it to SAP.
  • 8. • Functional test case using JUnit: • Public void functionalTest(){ • • File fXmlFile = new File(request.xml); • StringBuilder sb = new StringBuilder(); • BufferedReader br = new BufferedReader(new FileReader(fXmlFile)); • • String sCurrentLine = new String(); • //Read the data from file and append to string • while ((sCurrentLine = br.readLine()) != null) { • sb.append(sCurrentLine); • } • • DefaultHttpClient httpclient = new DefaultHttpClient(); • • HttpPost httppost = new HttpPost(requrl); • • httppost.setEntity(new StringEntity(sb.toString(), "UTF-8")); • //Trigger the service • HttpResponse response = httpclient.execute(httppost); • • ---- • ---- • } •
  • 9. • Flow of execution 1. Read the input request from request.xml file. 2. Trigger the service with above request. 3. Process the input request. 4. Transform the processed request to SAP IDoc and push it to SAP. • Issue • Here we are unable to mock the SAP component so the test case is directly pushing the IDoc to original SAP. • NOTE: Not only pushing the IDoc to SAP, at the time of receiving IDoc from SAP also we will
  • 11.
  • 12. • Flow of execution 1. Trigger the service with xml request. 2. Processes the input request. 3. Create the processed request as customer in Salesforce.
  • 13. • Functional Test Case • Public void functionalTest(){ • • File fXmlFile = new File(request.xml); • StringBuilder sb = new StringBuilder(); • BufferedReader br = new BufferedReader(new FileReader(fXmlFile)); • • String sCurrentLine = new String(); • // Read the data from file and append to string • while ((sCurrentLine = br.readLine()) != null) { • sb.append(sCurrentLine); • } • • DefaultHttpClient httpclient = new DefaultHttpClient(); • • HttpPost httppost = new HttpPost(requrl); • • httppost.setEntity(new StringEntity(sb.toString(), "UTF-8")); • //Trigger the service • HttpResponse response = httpclient.execute(httppost); • • ---- • ---- • }
  • 14. • Flow of Execution 1. First read the input request from request.xml file. 2. Trigger the service with above request. 3. Process the input request. 4. Create the customer in salesforce. • Issue • Here also we are unable to mock the Salesforce component so it will connect to original Salesforce connector and create the
  • 15. Solution • To resolve the above JUnit functional test case issue we have a separate framework called MUnit. MUnit is also one framework which is used to write test cases as same as JUnit, but here in MUnit we can mock all components like SAP, Salesforce, Database etc. So to overcome the above problem we can use MUnit to write functional test cases.
  • 16. • Example • Mocking Salesforce test case using Munit • .mflow • <?xml version="1.0" encoding="UTF-8"?> • • <mule xmlns="http://www.mulesoft.org/schema/mule/core" xmlns:vm="http://www.mulesoft.org/schema/mule/vm" xmlns:sfdc="http://www.mulesoft.org/schema/mule/sfdc" xmlns:doc="http://www.mulesoft.org/schema/mule/documentation" xmlns:spring="http://www.springframework.org/schema/beans" xmlns:core="http://www.mulesoft.org/schema/mule/core" version="EE-3.4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.mulesoft.org/schema/mule/vm http://www.mulesoft.org/schema/mule/vm/current/mule-vm.xsd • http://www.mulesoft.org/schema/mule/sfdc http://www.mulesoft.org/schema/mule/sfdc/5.0/mule-sfdc.xsd • http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-current.xsd • http://www.mulesoft.org/schema/mule/core http://www.mulesoft.org/schema/mule/core/current/mule.xsd"> • <vm:endpoint exchange-pattern="request-response" path="CREATE_CSTMR_VM" name="CREATE_CSTMR_VM" doc:name="VM"/> • <vm:endpoint exchange-pattern="request-response" path="INSERT_PERSON_ACT_VM" name="INSERT_PERSON_ACT_VM" doc:name="VM"/> • <flow name="CreateCustomerSFServiceTSFlow1" doc:name="CreateCustomerSFServiceTSFlow1"> • <vm:inbound-endpoint exchange-pattern="request-response" ref="CREATE_CSTMR_VM" doc:name="VM"/> • <component class="com.vertu.services.ecom.maintaincustmr.processor.CreateCustomerProcessor" doc:name="CreateCustomerProcessor"/> • </flow> • <flow name="CreateCustomerSFServiceTSFlow2" doc:name="CreateCustomerSFServiceTSFlow2"> • <vm:inbound-endpoint exchange-pattern="request-response" ref="INSERT_PERSON_ACT_VM" doc:name="VM"/> • <sfdc:create config-ref="ECOM_SALESFORCE_CONNECTOR" type="#[payload.Type]" doc:name="Salesforce"> • <sfdc:objects ref="#[payload.Object]"/> • </sfdc:create> • </flow> • </mule> • Here we have a Salesforce component to create the customer in Salesforce and return the customer-id as payload. So in functional test case we should mock this component without connecting to original Salesforce.
  • 17. • How to mock Salesforce component in MUnit functional test case • • To mock Salesforce component, first we should know • • Endpoint type. • Name of the message processor and namespace of endpoint (from auto-generated XML). • The type of payload the endpoint returns. • • • Mocking above flow Salesforce component • • Create the salesforce response payload. • • List<Map<String,Object>> l1 = new ArrayList<Map<String,Object>>(); • Map<String,Object> m1 = new HashMap<Srtring,Object>>(); • m1.put(“custid”,”1234”); • l1.add(m1); • • Mock the salesforce component and return the above created list as response payload. • • whenMessageProcessor("create").ofNamespace("sfdc").
  • 18. • MUnit functional test case for above flow • public class MUnitSalesforceStubTest extends FunctionalMunitSuite { • /** • * The purpose of this method is to define the list of flow • * files which will be loaded by Munit test case before executing • * Munit test case. Specify multiple flow files as comma • * separated XML files. • */ • @Override • protected String getConfigResources() { • return "src/main/app/MUnitSFTest.xml"; • } • /** • *The purpose of this method is to define the list of • flow name which will execute in Munit test case. • */ • protected List<String> getFlowsExcludedOfInboundDisabling(){ • List<String> list = new ArrayList<String>(); • list.add("CreateCustomerSFServiceTSFlow2"); • return list; • } • /** • * The purpose of this method is to flip between mock • * and real time interfaces. Return false to Mock • * all endpoints in your flow • */ • @Override • public boolean haveToMockMuleConnectors() { • return true; • }
  • 19. • /** • * Java based Munit test case. Contains mocking and • * invocation of flows and assertions. • */ • @Test • public void validateEchoFlow() throws Exception { • • List<Map<String,Object>> l1 = new ArrayList<Map<String,Object>>(); • Map<String,Object> m1 = new HashMap<Srtring,Object>>(); • m1.put(“custid”,”1234”); • l1.add(m1); • • // Mock SFDC outbound endpoint • whenMessageProcessor("query").ofNamespace("sfdc").thenReturn( muleMessageWithPayload( l1) ); • • // Run the Munit test case by passing a test payload • MuleEvent resultEvent = runFlow( " CreateCustomerSFServiceTSFlow1", testEvent(“request”)); • // The resultEvent contains response from the VM flow • System.out.println( "The flow response is:: " + resultEvent.getMessage().getPayloadAsString() ); • // Do any assertion here using Assert.equals() for asserting response // payload • } • }
  • 20. • Mocking Database component test case using MUnit • .mflow <flow name="CheckAcctIDFlow" doc:name="CheckAcctIDFlow"> <vm:inbound-endpoint exchange-pattern="request-response" ref="FETCH_ACT_GUID_VM1" doc:name="FETCH_ACT_GUID_VM1"/> <logger message="#[message.inboundProperties['ACCT_GUID']]" level="INFO" doc:name="Logger"/> <jdbc-ee:outbound-endpoint exchange-pattern="request- response" queryKey="Get_ACC_ID" queryTimeout="-1" connector- ref="CDMR_JDBC_CONNECTOR" doc:name="Get_ACCT_ID"/> </flow> • Here we have a database component used to select and return the account-id from database. So we need to mock this component in functional test case.
  • 21. • Mocking above flow Database component • • Create the database response payload. • • List<Map<String,Object>> l1 = new ArrayList<Map<String,Object>>(); • Map<String,Object> m1 = new HashMap<Srtring,Object>>(); • m1.put(“accountid”,”1234”); • l1.add(m1); • • Mock the database component and return the above created list as response payload. • • whenEndpointWithAddress( "jdbc://Get_ACC_ID" ).thenReturn(new DefaultMuleMessage(l1,
  • 22. • MUnit functional test case for above flow • public class MUnitSalesforceStubTest extends FunctionalMunitSuite { • /** • * The purpose of this method is to define the list of flow • * files which will be loaded by Munit test case before executing • * Munit test case. Specify multiple flow files as comma • * separated XML files. • */ • @Override • protected String getConfigResources() { • return "src/main/app/MUnitSFTest.xml"; • } • • /** • * The purpose of this method is to flip between mock • * and real time interfaces. Return false to Mock • * all endpoints in your flow • */ • @Override • public boolean haveToMockMuleConnectors() { • return true; • } • /** • * Java based Munit test case. Contains mocking and • * invocation of flows and assertions. • */ • @Test • public void validateEchoFlow() throws Exception { • • List<Map<String,Object>> l1 = new ArrayList<Map<String,Object>>(); • Map<String,Object> m1 = new HashMap<Srtring,Object>>(); • m1.put(“accountid”,”1234”); • l1.add(m1);
  • 23. • // Mock Database outbound endpoint • whenEndpointWithAddress( "jdbc://Get_ACC_ID" ).thenReturn(new DefaultMuleMessage(l1, muleContext ) ); • • // Run the Munit test case by passing a test payload • MuleEvent resultEvent = runFlow( " CheckAcctIDFlow ", testEvent(“request”)); • // The resultEvent contains response from the VM flow • System.out.println( "The flow response is:: " + resultEvent.getMessage().getPayloadAsString() ); • // Do any assertion here using Assert.equals() for asserting response // payload • } • }
  • 24. Benefits • Create Java based or Mule flow based unit test cases • Mock endpoints (Salesforce, Database, or SAP etc.) to return custom payloads for unit testing • Dynamically flip/parameterize Munit test cases to Mock payloads or use real time interfaces • Support functional unit testing similar to Mule Functional test case • Support Assertion through Spy processors and additionally verify flows using Message verifiers (introspect payload at different flows for flow navigation) • Support Asynchronous flow processing and request- response processors • Mock without custom database or in memory database • Automate test cases using Maven and generate HTML reports using Surefire plugins
  • 25. Conclusion • When we write test cases using JUnit we can’t mock all mule components and the test case will connect to original connectors(SAP, Salesforce). So to overcome this issue we can use MUnit to write test cases effectively.