SlideShare a Scribd company logo
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:
Junit in mule
• 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
Junit in mule
• 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
Ad

More Related Content

What's hot (18)

Mule new jdbc component
Mule new jdbc componentMule new jdbc component
Mule new jdbc component
Anirban Sen Chowdhary
 
For each component in mule
For each component in muleFor each component in mule
For each component in mule
Rajkattamuri
 
Maven introduction in Mule
Maven introduction in MuleMaven introduction in Mule
Maven introduction in Mule
Shahid Shaik
 
Mulesoft file connector
Mulesoft file connectorMulesoft file connector
Mulesoft file connector
kumar gaurav
 
Mule soa
Mule soaMule soa
Mule soa
Son Nguyen
 
Mule Esb Data Weave
Mule Esb Data WeaveMule Esb Data Weave
Mule Esb Data Weave
Mohammed246
 
Mule concepts connectors
Mule concepts connectorsMule concepts connectors
Mule concepts connectors
kunal vishe
 
Mule - HTTP Listener
Mule - HTTP ListenerMule - HTTP Listener
Mule - HTTP Listener
Ankush Sharma
 
Connectors in mule
Connectors in muleConnectors in mule
Connectors in mule
Sindhu VL
 
Vm component in mule
Vm component in muleVm component in mule
Vm component in mule
javeed_mhd
 
Mulesoft vm transport reference
Mulesoft vm transport referenceMulesoft vm transport reference
Mulesoft vm transport reference
kumar gaurav
 
Mule Requester Usage Demo
Mule Requester Usage DemoMule Requester Usage Demo
Mule Requester Usage Demo
Ramakrishna Narkedamilli
 
Mule dataweave
Mule dataweaveMule dataweave
Mule dataweave
Son Nguyen
 
Choice component in mule
Choice component in mule Choice component in mule
Choice component in mule
Rajkattamuri
 
Mule esb basic introduction
Mule esb basic introductionMule esb basic introduction
Mule esb basic introduction
Son Nguyen
 
Mule ESB - Mock Salesforce Interface
Mule ESB - Mock Salesforce InterfaceMule ESB - Mock Salesforce Interface
Mule ESB - Mock Salesforce Interface
krishananth
 
Junit in mule demo
Junit in mule demo Junit in mule demo
Junit in mule demo
javeed_mhd
 
Introduction to mule esb
Introduction to mule esbIntroduction to mule esb
Introduction to mule esb
Khasim Cise
 
For each component in mule
For each component in muleFor each component in mule
For each component in mule
Rajkattamuri
 
Maven introduction in Mule
Maven introduction in MuleMaven introduction in Mule
Maven introduction in Mule
Shahid Shaik
 
Mulesoft file connector
Mulesoft file connectorMulesoft file connector
Mulesoft file connector
kumar gaurav
 
Mule Esb Data Weave
Mule Esb Data WeaveMule Esb Data Weave
Mule Esb Data Weave
Mohammed246
 
Mule concepts connectors
Mule concepts connectorsMule concepts connectors
Mule concepts connectors
kunal vishe
 
Mule - HTTP Listener
Mule - HTTP ListenerMule - HTTP Listener
Mule - HTTP Listener
Ankush Sharma
 
Connectors in mule
Connectors in muleConnectors in mule
Connectors in mule
Sindhu VL
 
Vm component in mule
Vm component in muleVm component in mule
Vm component in mule
javeed_mhd
 
Mulesoft vm transport reference
Mulesoft vm transport referenceMulesoft vm transport reference
Mulesoft vm transport reference
kumar gaurav
 
Mule dataweave
Mule dataweaveMule dataweave
Mule dataweave
Son Nguyen
 
Choice component in mule
Choice component in mule Choice component in mule
Choice component in mule
Rajkattamuri
 
Mule esb basic introduction
Mule esb basic introductionMule esb basic introduction
Mule esb basic introduction
Son Nguyen
 
Mule ESB - Mock Salesforce Interface
Mule ESB - Mock Salesforce InterfaceMule ESB - Mock Salesforce Interface
Mule ESB - Mock Salesforce Interface
krishananth
 
Junit in mule demo
Junit in mule demo Junit in mule demo
Junit in mule demo
javeed_mhd
 
Introduction to mule esb
Introduction to mule esbIntroduction to mule esb
Introduction to mule esb
Khasim Cise
 

Viewers also liked (20)

Folder Duurzaam Communiceren met NLP
Folder Duurzaam Communiceren met NLPFolder Duurzaam Communiceren met NLP
Folder Duurzaam Communiceren met NLP
TeamInBalance
 
206.8 mario puga
206.8 mario puga206.8 mario puga
206.8 mario puga
dec-admin
 
Фотовыставка "Российский Северный Кавказ - на дороге перемен"
Фотовыставка "Российский Северный Кавказ - на дороге перемен"Фотовыставка "Российский Северный Кавказ - на дороге перемен"
Фотовыставка "Российский Северный Кавказ - на дороге перемен"
socreklama
 
Insurance company
Insurance companyInsurance company
Insurance company
astoeckling
 
Heroes ecologicos
Heroes ecologicosHeroes ecologicos
Heroes ecologicos
dec-admin
 
9.tumbate el rollo
9.tumbate el rollo9.tumbate el rollo
9.tumbate el rollo
dec-admin
 
H1336045813406八個覺悟一人幸福終老
H1336045813406八個覺悟一人幸福終老H1336045813406八個覺悟一人幸福終老
H1336045813406八個覺悟一人幸福終老
Tony Chen
 
Products & Services for Microelectronics
Products & Services for MicroelectronicsProducts & Services for Microelectronics
Products & Services for Microelectronics
Kamal Karimanal
 
164. juntos podemos llegar a la meta
164. juntos podemos llegar a la meta164. juntos podemos llegar a la meta
164. juntos podemos llegar a la meta
dec-admin
 
280. mejoramiento del entorno físico
280. mejoramiento del entorno físico280. mejoramiento del entorno físico
280. mejoramiento del entorno físico
dec-admin
 
Yo te doy las herramientas, tu construyes
Yo te doy las herramientas, tu construyesYo te doy las herramientas, tu construyes
Yo te doy las herramientas, tu construyes
dec-admin
 
ตลาดสำคัญในบางกอก กลุ่มที่ 4 ชั้นม.3 3
ตลาดสำคัญในบางกอก กลุ่มที่ 4 ชั้นม.3 3ตลาดสำคัญในบางกอก กลุ่มที่ 4 ชั้นม.3 3
ตลาดสำคัญในบางกอก กลุ่มที่ 4 ชั้นม.3 3
katnakamol
 
174.viva la familia
174.viva la familia174.viva la familia
174.viva la familia
dec-admin
 
Berry sour surprise
Berry sour surpriseBerry sour surprise
Berry sour surprise
astoeckling
 
Vivamos libres de acidentes.
Vivamos libres de acidentes. Vivamos libres de acidentes.
Vivamos libres de acidentes.
dec-admin
 
Mortgage Booklet
Mortgage BookletMortgage Booklet
Mortgage Booklet
leonpreser
 
Public ii cielution_imaps_chip_to_system_codesign
Public ii cielution_imaps_chip_to_system_codesignPublic ii cielution_imaps_chip_to_system_codesign
Public ii cielution_imaps_chip_to_system_codesign
Kamal Karimanal
 
Folder Duurzaam Communiceren met NLP
Folder Duurzaam Communiceren met NLPFolder Duurzaam Communiceren met NLP
Folder Duurzaam Communiceren met NLP
TeamInBalance
 
206.8 mario puga
206.8 mario puga206.8 mario puga
206.8 mario puga
dec-admin
 
Фотовыставка "Российский Северный Кавказ - на дороге перемен"
Фотовыставка "Российский Северный Кавказ - на дороге перемен"Фотовыставка "Российский Северный Кавказ - на дороге перемен"
Фотовыставка "Российский Северный Кавказ - на дороге перемен"
socreklama
 
Insurance company
Insurance companyInsurance company
Insurance company
astoeckling
 
Heroes ecologicos
Heroes ecologicosHeroes ecologicos
Heroes ecologicos
dec-admin
 
9.tumbate el rollo
9.tumbate el rollo9.tumbate el rollo
9.tumbate el rollo
dec-admin
 
H1336045813406八個覺悟一人幸福終老
H1336045813406八個覺悟一人幸福終老H1336045813406八個覺悟一人幸福終老
H1336045813406八個覺悟一人幸福終老
Tony Chen
 
Products & Services for Microelectronics
Products & Services for MicroelectronicsProducts & Services for Microelectronics
Products & Services for Microelectronics
Kamal Karimanal
 
164. juntos podemos llegar a la meta
164. juntos podemos llegar a la meta164. juntos podemos llegar a la meta
164. juntos podemos llegar a la meta
dec-admin
 
280. mejoramiento del entorno físico
280. mejoramiento del entorno físico280. mejoramiento del entorno físico
280. mejoramiento del entorno físico
dec-admin
 
Yo te doy las herramientas, tu construyes
Yo te doy las herramientas, tu construyesYo te doy las herramientas, tu construyes
Yo te doy las herramientas, tu construyes
dec-admin
 
ตลาดสำคัญในบางกอก กลุ่มที่ 4 ชั้นม.3 3
ตลาดสำคัญในบางกอก กลุ่มที่ 4 ชั้นม.3 3ตลาดสำคัญในบางกอก กลุ่มที่ 4 ชั้นม.3 3
ตลาดสำคัญในบางกอก กลุ่มที่ 4 ชั้นม.3 3
katnakamol
 
174.viva la familia
174.viva la familia174.viva la familia
174.viva la familia
dec-admin
 
Berry sour surprise
Berry sour surpriseBerry sour surprise
Berry sour surprise
astoeckling
 
Vivamos libres de acidentes.
Vivamos libres de acidentes. Vivamos libres de acidentes.
Vivamos libres de acidentes.
dec-admin
 
Mortgage Booklet
Mortgage BookletMortgage Booklet
Mortgage Booklet
leonpreser
 
Public ii cielution_imaps_chip_to_system_codesign
Public ii cielution_imaps_chip_to_system_codesignPublic ii cielution_imaps_chip_to_system_codesign
Public ii cielution_imaps_chip_to_system_codesign
Kamal Karimanal
 
Ad

Similar to Junit in mule (20)

J unit
J unitJ unit
J unit
Durga Prasad Kakarla
 
Junit in mule demo
Junit in mule demoJunit in mule demo
Junit in mule demo
Sudha Ch
 
Munit junit test case
Munit junit test caseMunit junit test case
Munit junit test case
prudhvivreddy
 
Mocking with salesforce using Munit
Mocking with salesforce using MunitMocking with salesforce using Munit
Mocking with salesforce using Munit
Son Nguyen
 
Spring batch
Spring batchSpring batch
Spring batch
Chandan Kumar Rana
 
JavaScript for real men
JavaScript for real menJavaScript for real men
JavaScript for real men
Ivano Malavolta
 
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
 
Javascript
JavascriptJavascript
Javascript
Sun Technlogies
 
Test driven development
Test driven developmentTest driven development
Test driven development
christoforosnalmpantis
 
Salesforce asynchronous apex
Salesforce asynchronous apexSalesforce asynchronous apex
Salesforce asynchronous apex
Badan Singh Pundeer
 
Introduction to C ++.pptx
Introduction to C ++.pptxIntroduction to C ++.pptx
Introduction to C ++.pptx
VAIBHAVKADAGANCHI
 
Performance Tuning and Optimization
Performance Tuning and OptimizationPerformance Tuning and Optimization
Performance Tuning and Optimization
MongoDB
 
Unit Testing
Unit TestingUnit Testing
Unit Testing
Stanislav Tiurikov
 
How to use batch component
How to use batch componentHow to use batch component
How to use batch component
sivachandra mandalapu
 
BITM3730 10-3.pptx
BITM3730 10-3.pptxBITM3730 10-3.pptx
BITM3730 10-3.pptx
MattMarino13
 
Rdbms chapter 1 function
Rdbms chapter 1 functionRdbms chapter 1 function
Rdbms chapter 1 function
dipumaliy
 
BITM3730 10-4.pptx
BITM3730 10-4.pptxBITM3730 10-4.pptx
BITM3730 10-4.pptx
MattMarino13
 
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
Vibrant Technologies & Computers
 
ServiceNow Knowledge11 Advanced Scripting & Debugging Lab
ServiceNow Knowledge11 Advanced Scripting & Debugging LabServiceNow Knowledge11 Advanced Scripting & Debugging Lab
ServiceNow Knowledge11 Advanced Scripting & Debugging Lab
John Roberts
 
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
 
Junit in mule demo
Junit in mule demoJunit in mule demo
Junit in mule demo
Sudha Ch
 
Munit junit test case
Munit junit test caseMunit junit test case
Munit junit test case
prudhvivreddy
 
Mocking with salesforce using Munit
Mocking with salesforce using MunitMocking with salesforce using Munit
Mocking with salesforce using Munit
Son Nguyen
 
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
 
Performance Tuning and Optimization
Performance Tuning and OptimizationPerformance Tuning and Optimization
Performance Tuning and Optimization
MongoDB
 
BITM3730 10-3.pptx
BITM3730 10-3.pptxBITM3730 10-3.pptx
BITM3730 10-3.pptx
MattMarino13
 
Rdbms chapter 1 function
Rdbms chapter 1 functionRdbms chapter 1 function
Rdbms chapter 1 function
dipumaliy
 
BITM3730 10-4.pptx
BITM3730 10-4.pptxBITM3730 10-4.pptx
BITM3730 10-4.pptx
MattMarino13
 
ServiceNow Knowledge11 Advanced Scripting & Debugging Lab
ServiceNow Knowledge11 Advanced Scripting & Debugging LabServiceNow Knowledge11 Advanced Scripting & Debugging Lab
ServiceNow Knowledge11 Advanced Scripting & Debugging Lab
John Roberts
 
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
 
Ad

More from Sunil Komarapu (20)

WebServices
WebServicesWebServices
WebServices
Sunil Komarapu
 
Maven
MavenMaven
Maven
Sunil Komarapu
 
Mule for each scope headerc ollection
Mule for each scope headerc ollectionMule for each scope headerc ollection
Mule for each scope headerc ollection
Sunil Komarapu
 
Mule esb Basics
Mule esb BasicsMule esb Basics
Mule esb Basics
Sunil Komarapu
 
Mule esb stripe
Mule esb stripeMule esb stripe
Mule esb stripe
Sunil Komarapu
 
Mule esb api layer
Mule esb api layerMule esb api layer
Mule esb api layer
Sunil Komarapu
 
Mmc rest api user groups
Mmc rest api user groupsMmc rest api user groups
Mmc rest api user groups
Sunil Komarapu
 
Mapping and listing with mule
Mapping and listing with muleMapping and listing with mule
Mapping and listing with mule
Sunil Komarapu
 
How to use message properties component
How to use message properties componentHow to use message properties component
How to use message properties component
Sunil Komarapu
 
How to use expression filter
How to use expression filterHow to use expression filter
How to use expression filter
Sunil Komarapu
 
Data weave
Data weave Data weave
Data weave
Sunil Komarapu
 
Anypoint data gateway
Anypoint data gatewayAnypoint data gateway
Anypoint data gateway
Sunil Komarapu
 
Caching and invalidating with managed store
Caching and invalidating with managed storeCaching and invalidating with managed store
Caching and invalidating with managed store
Sunil Komarapu
 
Automatic documantation with mule
Automatic documantation with muleAutomatic documantation with mule
Automatic documantation with mule
Sunil Komarapu
 
Cache for community edition
Cache for community editionCache for community edition
Cache for community edition
Sunil Komarapu
 
Caching and invalidating with managed store
Caching and invalidating with managed storeCaching and invalidating with managed store
Caching and invalidating with managed store
Sunil Komarapu
 
Converting with custom transformer
Converting with custom transformerConverting with custom transformer
Converting with custom transformer
Sunil Komarapu
 
Creating dynamic json
Creating dynamic jsonCreating dynamic json
Creating dynamic json
Sunil Komarapu
 
Groovy with mule
Groovy with muleGroovy with mule
Groovy with mule
Sunil Komarapu
 
Idempotent filter with simple file
Idempotent filter with simple fileIdempotent filter with simple file
Idempotent filter with simple file
Sunil Komarapu
 
Mule for each scope headerc ollection
Mule for each scope headerc ollectionMule for each scope headerc ollection
Mule for each scope headerc ollection
Sunil Komarapu
 
Mmc rest api user groups
Mmc rest api user groupsMmc rest api user groups
Mmc rest api user groups
Sunil Komarapu
 
Mapping and listing with mule
Mapping and listing with muleMapping and listing with mule
Mapping and listing with mule
Sunil Komarapu
 
How to use message properties component
How to use message properties componentHow to use message properties component
How to use message properties component
Sunil Komarapu
 
How to use expression filter
How to use expression filterHow to use expression filter
How to use expression filter
Sunil Komarapu
 
Caching and invalidating with managed store
Caching and invalidating with managed storeCaching and invalidating with managed store
Caching and invalidating with managed store
Sunil Komarapu
 
Automatic documantation with mule
Automatic documantation with muleAutomatic documantation with mule
Automatic documantation with mule
Sunil Komarapu
 
Cache for community edition
Cache for community editionCache for community edition
Cache for community edition
Sunil Komarapu
 
Caching and invalidating with managed store
Caching and invalidating with managed storeCaching and invalidating with managed store
Caching and invalidating with managed store
Sunil Komarapu
 
Converting with custom transformer
Converting with custom transformerConverting with custom transformer
Converting with custom transformer
Sunil Komarapu
 
Idempotent filter with simple file
Idempotent filter with simple fileIdempotent filter with simple file
Idempotent filter with simple file
Sunil Komarapu
 

Recently uploaded (20)

Linux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdfLinux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdf
RHCSA Guru
 
Technology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data AnalyticsTechnology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data Analytics
InData Labs
 
Mobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi ArabiaMobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi Arabia
Steve Jonas
 
Role of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered ManufacturingRole of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered Manufacturing
Andrew Leo
 
Build Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For DevsBuild Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For Devs
Brian McKeiver
 
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdfThe Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
Abi john
 
Rusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond SparkRusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond Spark
carlyakerly1
 
2025-05-Q4-2024-Investor-Presentation.pptx
2025-05-Q4-2024-Investor-Presentation.pptx2025-05-Q4-2024-Investor-Presentation.pptx
2025-05-Q4-2024-Investor-Presentation.pptx
Samuele Fogagnolo
 
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdfSAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
Precisely
 
What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...
Vishnu Singh Chundawat
 
Generative Artificial Intelligence (GenAI) in Business
Generative Artificial Intelligence (GenAI) in BusinessGenerative Artificial Intelligence (GenAI) in Business
Generative Artificial Intelligence (GenAI) in Business
Dr. Tathagat Varma
 
Splunk Security Update | Public Sector Summit Germany 2025
Splunk Security Update | Public Sector Summit Germany 2025Splunk Security Update | Public Sector Summit Germany 2025
Splunk Security Update | Public Sector Summit Germany 2025
Splunk
 
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptxDevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
Justin Reock
 
HCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser EnvironmentsHCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser Environments
panagenda
 
Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdfComplete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Software Company
 
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In France
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In FranceManifest Pre-Seed Update | A Humanoid OEM Deeptech In France
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In France
chb3
 
Andrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell: Transforming Business Strategy Through Data-Driven InsightsAndrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell
 
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
BookNet Canada
 
Drupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy ConsumptionDrupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy Consumption
Exove
 
Semantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AISemantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AI
artmondano
 
Linux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdfLinux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdf
RHCSA Guru
 
Technology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data AnalyticsTechnology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data Analytics
InData Labs
 
Mobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi ArabiaMobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi Arabia
Steve Jonas
 
Role of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered ManufacturingRole of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered Manufacturing
Andrew Leo
 
Build Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For DevsBuild Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For Devs
Brian McKeiver
 
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdfThe Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
Abi john
 
Rusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond SparkRusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond Spark
carlyakerly1
 
2025-05-Q4-2024-Investor-Presentation.pptx
2025-05-Q4-2024-Investor-Presentation.pptx2025-05-Q4-2024-Investor-Presentation.pptx
2025-05-Q4-2024-Investor-Presentation.pptx
Samuele Fogagnolo
 
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdfSAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
Precisely
 
What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...
Vishnu Singh Chundawat
 
Generative Artificial Intelligence (GenAI) in Business
Generative Artificial Intelligence (GenAI) in BusinessGenerative Artificial Intelligence (GenAI) in Business
Generative Artificial Intelligence (GenAI) in Business
Dr. Tathagat Varma
 
Splunk Security Update | Public Sector Summit Germany 2025
Splunk Security Update | Public Sector Summit Germany 2025Splunk Security Update | Public Sector Summit Germany 2025
Splunk Security Update | Public Sector Summit Germany 2025
Splunk
 
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptxDevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
Justin Reock
 
HCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser EnvironmentsHCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser Environments
panagenda
 
Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdfComplete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Software Company
 
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In France
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In FranceManifest Pre-Seed Update | A Humanoid OEM Deeptech In France
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In France
chb3
 
Andrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell: Transforming Business Strategy Through Data-Driven InsightsAndrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell
 
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
BookNet Canada
 
Drupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy ConsumptionDrupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy Consumption
Exove
 
Semantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AISemantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AI
artmondano
 

Junit in mule

  • 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:
  • 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
  • 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.