SlideShare a Scribd company logo
1 of 31
JUnit Functional test cases
By: Prudhvi
25-July-2015
Abstract
The main theme of this is what the issues to write test
cases using JUnit are and how to overcome those
issues.
Contents
1. ABSTRACT
2. INTRODUCTION
3. PROBLEM STATEMENT
4. SOLUTION
5. CONCLUSION
6. REFERENCE
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
Trigger the service with xml request.
Receive the input request and process it.
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 face same issue.
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
customer on it.
Sample flow
<?xml version="1.0" encoding="UTF-8"?> <mule xmlns:http="http://www.mulesoft.org/schema/mule/http"
xmlns:tracking="http://www.mulesoft.org/schema/mule/ee/tracking"
xmlns="http://www.mulesoft.org/schema/mule/core"
xmlns:doc="http://www.mulesoft.org/schema/mule/documentation"
xmlns:spring="http://www.springframework.org/schema/beans" version="EE-3.6.1"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="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
http://www.mulesoft.org/schema/mule/ee/tracking
http://www.mulesoft.org/schema/mule/ee/tracking/current/mule-tracking-ee.xsd
http://www.mulesoft.org/schema/mule/http http://www.mulesoft.org/schema/mule/http/current/mule-http.xsd">
<http:listener-config name="HTTP_Listener_Configuration" host="0.0.0.0" port="9090" doc:name="HTTP Listener
Configuration"/> <flow name="exampleFlow"> <http:listener config-ref="HTTP_Listener_Configuration" path="/"
allowedMethods="GET" doc:name="HTTP"/> <set-payload
value="#[message.inboundProperties['http.query.params']['url_key']]" doc:name="Set Original Payload"/> <flow-ref
name="exampleFlow2" doc:name="exampleFlow2"/> <choice doc:name="Choice"> <when
expression="#[flowVars['my_variable'].equals('var_value_1')]"> <set-payload value="#['response_payload_1']"
doc:name="Set Response Payload"/> </when> <otherwise> <set-payload value="#['response_payload_2']"
doc:name="Set Response Payload"/> </otherwise> </choice> </flow> <flow name="exampleFlow2"> <choice
doc:name="Choice"> <when expression="#['payload_1'.equals(payload)]"> <flow-ref name="exampleSub_Flow1"
doc:name="exampleSub_Flow1"/> </when> <otherwise> <flow-ref name="exampleSub_Flow2"
doc:name="exampleSub_Flow2"/> </otherwise> </choice> </flow> <sub-flow name="exampleSub_Flow1"> <set-
variable variableName="my_variable" value="#['var_value_1']" doc:name="my_variable"/> </sub-flow> <sub-flow
name="exampleSub_Flow2"> <set-variable variableName="my_variable" value="#['var_value_2']"
doc:name="my_variable"/> </sub-flow> </mule>
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
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").
thenReturn( muleMessageWithPayload( 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 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").thenRetu
rn( 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, muleContext ) );
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>>();
// 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/display/EARLYACCE
SS/MUnit
About the Author
Prudhvi

More Related Content

What's hot

Unit testing and MVVM in Silverlight
Unit testing and MVVM in SilverlightUnit testing and MVVM in Silverlight
Unit testing and MVVM in Silverlight
Devnology
 
Performance testing using Jmeter for apps which needs authentication
Performance testing using Jmeter for apps which needs authenticationPerformance testing using Jmeter for apps which needs authentication
Performance testing using Jmeter for apps which needs authentication
Jay Jha
 

What's hot (20)

Anypoint mq acknowledgement mode
Anypoint mq acknowledgement modeAnypoint mq acknowledgement mode
Anypoint mq acknowledgement mode
 
Test automation in Loris
Test automation in LorisTest automation in Loris
Test automation in Loris
 
Quartz component in mule
Quartz component in muleQuartz component in mule
Quartz component in mule
 
Filter expression in mule
Filter expression in muleFilter expression in mule
Filter expression in mule
 
Mule management console installation with Tomcat
Mule management console installation with TomcatMule management console installation with Tomcat
Mule management console installation with Tomcat
 
Unit testing and MVVM in Silverlight
Unit testing and MVVM in SilverlightUnit testing and MVVM in Silverlight
Unit testing and MVVM in Silverlight
 
MUnit run and wait scope
MUnit run and wait scopeMUnit run and wait scope
MUnit run and wait scope
 
Mule esb add logger to existing flow
Mule esb add logger to existing flowMule esb add logger to existing flow
Mule esb add logger to existing flow
 
Real-world Model-View-ViewModel for WPF
Real-world Model-View-ViewModel for WPFReal-world Model-View-ViewModel for WPF
Real-world Model-View-ViewModel for WPF
 
Java components in mule
Java components in muleJava components in mule
Java components in mule
 
ASP.Net MVC 4 [Part - 2]
ASP.Net MVC 4 [Part - 2]ASP.Net MVC 4 [Part - 2]
ASP.Net MVC 4 [Part - 2]
 
Snow Leopard
Snow LeopardSnow Leopard
Snow Leopard
 
Mule using Salesforce
Mule using SalesforceMule using Salesforce
Mule using Salesforce
 
Mule esb :Data Weave
Mule esb :Data WeaveMule esb :Data Weave
Mule esb :Data Weave
 
Performance testing using Jmeter for apps which needs authentication
Performance testing using Jmeter for apps which needs authenticationPerformance testing using Jmeter for apps which needs authentication
Performance testing using Jmeter for apps which needs authentication
 
Less10 2 e_testermodule_9
Less10 2 e_testermodule_9Less10 2 e_testermodule_9
Less10 2 e_testermodule_9
 
Bindings of components in mule
Bindings of components in muleBindings of components in mule
Bindings of components in mule
 
What Is JMeter?
What Is JMeter?What Is JMeter?
What Is JMeter?
 
Idempotent filter in mule
Idempotent filter in muleIdempotent filter in mule
Idempotent filter in mule
 
Idempotent filter in Mule
Idempotent filter in MuleIdempotent filter in Mule
Idempotent filter in Mule
 

Similar to Munit junit test case

Assignment 02 Process State SimulationCSci 430 Introduction to.docx
Assignment 02 Process State SimulationCSci 430 Introduction to.docxAssignment 02 Process State SimulationCSci 430 Introduction to.docx
Assignment 02 Process State SimulationCSci 430 Introduction to.docx
cargillfilberto
 

Similar to Munit junit test case (20)

J unit
J unitJ unit
J unit
 
Junit in mule
Junit in muleJunit in mule
Junit in mule
 
Junit in mule
Junit in muleJunit in mule
Junit in mule
 
Junit in mule
Junit in muleJunit in mule
Junit in mule
 
Enjoy Munit with Mule
Enjoy Munit with MuleEnjoy Munit with Mule
Enjoy Munit with Mule
 
Mule ESB - Mock Salesforce Interface
Mule ESB - Mock Salesforce InterfaceMule ESB - Mock Salesforce Interface
Mule ESB - Mock Salesforce Interface
 
jBPM5 Community Training Module 4: jBPM5 APIs Overview + Hands On
jBPM5 Community Training Module 4: jBPM5 APIs Overview + Hands OnjBPM5 Community Training Module 4: jBPM5 APIs Overview + Hands On
jBPM5 Community Training Module 4: jBPM5 APIs Overview + Hands On
 
Understanding Framework Architecture using Eclipse
Understanding Framework Architecture using EclipseUnderstanding Framework Architecture using Eclipse
Understanding Framework Architecture using Eclipse
 
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
 
Assignment 02 Process State SimulationCSci 430 Introduction to.docx
Assignment 02 Process State SimulationCSci 430 Introduction to.docxAssignment 02 Process State SimulationCSci 430 Introduction to.docx
Assignment 02 Process State SimulationCSci 430 Introduction to.docx
 
Sql storeprocedure
Sql storeprocedureSql storeprocedure
Sql storeprocedure
 
Android Application Development - Level 3
Android Application Development - Level 3Android Application Development - Level 3
Android Application Development - Level 3
 
Salesforce asynchronous apex
Salesforce asynchronous apexSalesforce asynchronous apex
Salesforce asynchronous apex
 
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
 
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
 
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
 
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
 
Adding a modern twist to legacy web applications
Adding a modern twist to legacy web applicationsAdding a modern twist to legacy web applications
Adding a modern twist to legacy web applications
 
Email using mule
Email using muleEmail using mule
Email using mule
 
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
 

More from prudhvivreddy

More from prudhvivreddy (20)

About Mule execution units
About Mule execution unitsAbout Mule execution units
About Mule execution units
 
Working with components
Working with componentsWorking with components
Working with components
 
About mule transformers
About mule transformersAbout mule transformers
About mule transformers
 
About jms
About jmsAbout jms
About jms
 
Webservices
WebservicesWebservices
Webservices
 
Generating the mule flow as html document
Generating the mule flow as html documentGenerating the mule flow as html document
Generating the mule flow as html document
 
Sftp connector
Sftp connectorSftp connector
Sftp connector
 
Imap connector
Imap connectorImap connector
Imap connector
 
Ftp connector
Ftp connectorFtp connector
Ftp connector
 
Hdfs connector
Hdfs connectorHdfs connector
Hdfs connector
 
Ajax connector
Ajax connectorAjax connector
Ajax connector
 
Basic example using vm component
Basic example using vm componentBasic example using vm component
Basic example using vm component
 
Basic example using until successful component
Basic example using until successful componentBasic example using until successful component
Basic example using until successful component
 
Basic example using message properties component
Basic example using message properties componentBasic example using message properties component
Basic example using message properties component
 
Basic example using for each component
Basic example using for each componentBasic example using for each component
Basic example using for each component
 
Basic example using database component
Basic example using database componentBasic example using database component
Basic example using database component
 
Basic example using choice component
Basic example using choice componentBasic example using choice component
Basic example using choice component
 
Basic example using file connector in anypoint studio
Basic example using file connector in anypoint studioBasic example using file connector in anypoint studio
Basic example using file connector in anypoint studio
 
Basic example using quartz component in anypoint studio
Basic example using quartz component in anypoint studioBasic example using quartz component in anypoint studio
Basic example using quartz component in anypoint studio
 
Mule fundamentals
Mule fundamentalsMule fundamentals
Mule fundamentals
 

Recently uploaded

Recently uploaded (20)

GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
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
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
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...
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
A Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source MilvusA Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source Milvus
 
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...
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu SubbuApidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 

Munit junit test case

  • 1. JUnit Functional test cases By: Prudhvi 25-July-2015
  • 2. Abstract The main theme of this is what the issues to write test cases using JUnit are and how to overcome those issues.
  • 3. Contents 1. ABSTRACT 2. INTRODUCTION 3. PROBLEM STATEMENT 4. SOLUTION 5. CONCLUSION 6. REFERENCE
  • 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.
  • 7. Flow of execution Trigger the service with xml request. Receive the input request and process it. 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 face same issue.
  • 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 customer on it.
  • 15. Sample flow <?xml version="1.0" encoding="UTF-8"?> <mule xmlns:http="http://www.mulesoft.org/schema/mule/http" xmlns:tracking="http://www.mulesoft.org/schema/mule/ee/tracking" xmlns="http://www.mulesoft.org/schema/mule/core" xmlns:doc="http://www.mulesoft.org/schema/mule/documentation" xmlns:spring="http://www.springframework.org/schema/beans" version="EE-3.6.1" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="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 http://www.mulesoft.org/schema/mule/ee/tracking http://www.mulesoft.org/schema/mule/ee/tracking/current/mule-tracking-ee.xsd http://www.mulesoft.org/schema/mule/http http://www.mulesoft.org/schema/mule/http/current/mule-http.xsd"> <http:listener-config name="HTTP_Listener_Configuration" host="0.0.0.0" port="9090" doc:name="HTTP Listener Configuration"/> <flow name="exampleFlow"> <http:listener config-ref="HTTP_Listener_Configuration" path="/" allowedMethods="GET" doc:name="HTTP"/> <set-payload value="#[message.inboundProperties['http.query.params']['url_key']]" doc:name="Set Original Payload"/> <flow-ref name="exampleFlow2" doc:name="exampleFlow2"/> <choice doc:name="Choice"> <when expression="#[flowVars['my_variable'].equals('var_value_1')]"> <set-payload value="#['response_payload_1']" doc:name="Set Response Payload"/> </when> <otherwise> <set-payload value="#['response_payload_2']" doc:name="Set Response Payload"/> </otherwise> </choice> </flow> <flow name="exampleFlow2"> <choice doc:name="Choice"> <when expression="#['payload_1'.equals(payload)]"> <flow-ref name="exampleSub_Flow1" doc:name="exampleSub_Flow1"/> </when> <otherwise> <flow-ref name="exampleSub_Flow2" doc:name="exampleSub_Flow2"/> </otherwise> </choice> </flow> <sub-flow name="exampleSub_Flow1"> <set- variable variableName="my_variable" value="#['var_value_1']" doc:name="my_variable"/> </sub-flow> <sub-flow name="exampleSub_Flow2"> <set-variable variableName="my_variable" value="#['var_value_2']" doc:name="my_variable"/> </sub-flow> </mule>
  • 16. 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.
  • 17. 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
  • 18. 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"). thenReturn( muleMessageWithPayload( l1) );
  • 19. 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. */
  • 20. 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; }
  • 21. /** * 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").thenRetu rn( muleMessageWithPayload( l1) );
  • 22. // 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 } }
  • 23. 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.
  • 24. 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, muleContext ) );
  • 25. 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"; }
  • 26. /** * 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>>();
  • 27. // 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 } }
  • 28. 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
  • 29. 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.