SlideShare a Scribd company logo
1 of 23
JUnit Functional Test Cases
By: Durga Prasad K
09-Dec-2015
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.
Introduction
• We have multiple unit test frameworks to
write unit and functional test cases for our
services. When we write functional test cases
using JUnit we can’t mock mule components.
To resolve this issues we have to use MUnit
and I am going to explain what is the problem
with JUnit and how to resolve using MUnit in
the below.
Problem Statement
• When we write functional test cases using JUnit, the test case will
directly connect to original components like SAP, Salesforce etc. and
insert/select the data. It is the issue in JUnit functional test case
why because we are writing functional test cases to check whether
entire functionality is working as expected or not without modifying
the original components(SAP,Salesforce,Database) data, but in JUnit
functional test cases it is directly connecting to original components
and modifying the original data.
• Examples:
1. SAP Connector
• Mule flow:
• Flow of execution
1. Trigger the service with xml request.
2. Receive the input request and process it.
3. Transform the processed request to SAP IDoc
and push it to SAP.
• Functional test case using JUnit:
• Public void functionalTest(){
•
• File fXmlFile = new File(request.xml);
• StringBuilder sb = new StringBuilder();
• BufferedReader br = new BufferedReader(new FileReader(fXmlFile));
•
• String sCurrentLine = new String();
• //Read the data from file and append to string
• while ((sCurrentLine = br.readLine()) != null) {
• sb.append(sCurrentLine);
• }
•
• DefaultHttpClient httpclient = new DefaultHttpClient();
•
• HttpPost httppost = new HttpPost(requrl);
•
• httppost.setEntity(new StringEntity(sb.toString(), "UTF-8"));
• //Trigger the service
• HttpResponse response = httpclient.execute(httppost);
•
• ----
• ----
• }
•
• Flow of execution
1. Read the input request from request.xml file.
2. Trigger the service with above request.
3. Process the input request.
4. Transform the processed request to SAP IDoc and
push it to SAP.
• Issue
• Here we are unable to mock the SAP component
so the test case is directly pushing the IDoc to
original SAP.
• NOTE: Not only pushing the IDoc to SAP, at the
time of receiving IDoc from SAP also we will 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.
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").
• 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").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, 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>>();
• 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

More Related Content

What's hot

How to build to do app using vue composition api and vuex 4 with typescript
How to build to do app using vue composition api and vuex 4 with typescriptHow to build to do app using vue composition api and vuex 4 with typescript
How to build to do app using vue composition api and vuex 4 with typescriptKaty Slemon
 
WINDOWS ADMINISTRATION AND WORKING WITH OBJECTS : PowerShell ISE
WINDOWS ADMINISTRATION AND WORKING WITH OBJECTS : PowerShell ISEWINDOWS ADMINISTRATION AND WORKING WITH OBJECTS : PowerShell ISE
WINDOWS ADMINISTRATION AND WORKING WITH OBJECTS : PowerShell ISEHitesh Mohapatra
 
Troubleshooting MySQL Performance add-ons
Troubleshooting MySQL Performance add-onsTroubleshooting MySQL Performance add-ons
Troubleshooting MySQL Performance add-onsSveta Smirnova
 
WPF and Prism 4.1 Workshop at BASTA Austria
WPF and Prism 4.1 Workshop at BASTA AustriaWPF and Prism 4.1 Workshop at BASTA Austria
WPF and Prism 4.1 Workshop at BASTA AustriaRainer Stropek
 
Java servlet life cycle - methods ppt
Java servlet life cycle - methods pptJava servlet life cycle - methods ppt
Java servlet life cycle - methods pptkamal kotecha
 
Concurrency Utilities in Java 8
Concurrency Utilities in Java 8Concurrency Utilities in Java 8
Concurrency Utilities in Java 8Martin Toshev
 
Introduction to Active Record at MySQL Conference 2007
Introduction to Active Record at MySQL Conference 2007Introduction to Active Record at MySQL Conference 2007
Introduction to Active Record at MySQL Conference 2007Rabble .
 
Jdbc example program with access and MySql
Jdbc example program with access and MySqlJdbc example program with access and MySql
Jdbc example program with access and MySqlkamal kotecha
 
Database connect
Database connectDatabase connect
Database connectYoga Raja
 
[스프링/Spring교육학원,자바교육,근로자교육,실업자교육추천학원_탑크리에듀]#6.스프링프레임워크 & 마이바티스 (Spring Framew...
[스프링/Spring교육학원,자바교육,근로자교육,실업자교육추천학원_탑크리에듀]#6.스프링프레임워크 & 마이바티스 (Spring Framew...[스프링/Spring교육학원,자바교육,근로자교육,실업자교육추천학원_탑크리에듀]#6.스프링프레임워크 & 마이바티스 (Spring Framew...
[스프링/Spring교육학원,자바교육,근로자교육,실업자교육추천학원_탑크리에듀]#6.스프링프레임워크 & 마이바티스 (Spring Framew...탑크리에듀(구로디지털단지역3번출구 2분거리)
 
MicroProfile: A Quest for a Lightweight and Modern Enterprise Java Platform
MicroProfile: A Quest for a Lightweight and Modern Enterprise Java PlatformMicroProfile: A Quest for a Lightweight and Modern Enterprise Java Platform
MicroProfile: A Quest for a Lightweight and Modern Enterprise Java PlatformMike Croft
 
JSP- JAVA SERVER PAGES
JSP- JAVA SERVER PAGESJSP- JAVA SERVER PAGES
JSP- JAVA SERVER PAGESYoga Raja
 
Mathemetics module
Mathemetics moduleMathemetics module
Mathemetics modulemanikanta361
 
Java Servlet
Java ServletJava Servlet
Java ServletYoga Raja
 
Introduction to JDBC and database access in web applications
Introduction to JDBC and database access in web applicationsIntroduction to JDBC and database access in web applications
Introduction to JDBC and database access in web applicationsFulvio Corno
 
EMCLI Crash Course - DOAG Germany
EMCLI Crash Course - DOAG GermanyEMCLI Crash Course - DOAG Germany
EMCLI Crash Course - DOAG GermanyGokhan Atil
 

What's hot (19)

How to build to do app using vue composition api and vuex 4 with typescript
How to build to do app using vue composition api and vuex 4 with typescriptHow to build to do app using vue composition api and vuex 4 with typescript
How to build to do app using vue composition api and vuex 4 with typescript
 
WINDOWS ADMINISTRATION AND WORKING WITH OBJECTS : PowerShell ISE
WINDOWS ADMINISTRATION AND WORKING WITH OBJECTS : PowerShell ISEWINDOWS ADMINISTRATION AND WORKING WITH OBJECTS : PowerShell ISE
WINDOWS ADMINISTRATION AND WORKING WITH OBJECTS : PowerShell ISE
 
Troubleshooting MySQL Performance add-ons
Troubleshooting MySQL Performance add-onsTroubleshooting MySQL Performance add-ons
Troubleshooting MySQL Performance add-ons
 
WPF and Prism 4.1 Workshop at BASTA Austria
WPF and Prism 4.1 Workshop at BASTA AustriaWPF and Prism 4.1 Workshop at BASTA Austria
WPF and Prism 4.1 Workshop at BASTA Austria
 
Java servlet life cycle - methods ppt
Java servlet life cycle - methods pptJava servlet life cycle - methods ppt
Java servlet life cycle - methods ppt
 
Concurrency Utilities in Java 8
Concurrency Utilities in Java 8Concurrency Utilities in Java 8
Concurrency Utilities in Java 8
 
Introduction to Active Record at MySQL Conference 2007
Introduction to Active Record at MySQL Conference 2007Introduction to Active Record at MySQL Conference 2007
Introduction to Active Record at MySQL Conference 2007
 
Jdbc example program with access and MySql
Jdbc example program with access and MySqlJdbc example program with access and MySql
Jdbc example program with access and MySql
 
Database connect
Database connectDatabase connect
Database connect
 
[스프링/Spring교육학원,자바교육,근로자교육,실업자교육추천학원_탑크리에듀]#6.스프링프레임워크 & 마이바티스 (Spring Framew...
[스프링/Spring교육학원,자바교육,근로자교육,실업자교육추천학원_탑크리에듀]#6.스프링프레임워크 & 마이바티스 (Spring Framew...[스프링/Spring교육학원,자바교육,근로자교육,실업자교육추천학원_탑크리에듀]#6.스프링프레임워크 & 마이바티스 (Spring Framew...
[스프링/Spring교육학원,자바교육,근로자교육,실업자교육추천학원_탑크리에듀]#6.스프링프레임워크 & 마이바티스 (Spring Framew...
 
Jdbc[1]
Jdbc[1]Jdbc[1]
Jdbc[1]
 
MicroProfile: A Quest for a Lightweight and Modern Enterprise Java Platform
MicroProfile: A Quest for a Lightweight and Modern Enterprise Java PlatformMicroProfile: A Quest for a Lightweight and Modern Enterprise Java Platform
MicroProfile: A Quest for a Lightweight and Modern Enterprise Java Platform
 
Autonomous transaction
Autonomous transactionAutonomous transaction
Autonomous transaction
 
JSP- JAVA SERVER PAGES
JSP- JAVA SERVER PAGESJSP- JAVA SERVER PAGES
JSP- JAVA SERVER PAGES
 
Refreshing mule cache using oracle database change notification
Refreshing mule cache using oracle database change notificationRefreshing mule cache using oracle database change notification
Refreshing mule cache using oracle database change notification
 
Mathemetics module
Mathemetics moduleMathemetics module
Mathemetics module
 
Java Servlet
Java ServletJava Servlet
Java Servlet
 
Introduction to JDBC and database access in web applications
Introduction to JDBC and database access in web applicationsIntroduction to JDBC and database access in web applications
Introduction to JDBC and database access in web applications
 
EMCLI Crash Course - DOAG Germany
EMCLI Crash Course - DOAG GermanyEMCLI Crash Course - DOAG Germany
EMCLI Crash Course - DOAG Germany
 

Similar to J unit

Junit in mule
Junit in muleJunit in mule
Junit in muleF K
 
Junit in mule demo
Junit in mule demo Junit in mule demo
Junit in mule demo javeed_mhd
 
Enjoy Munit with Mule
Enjoy Munit with MuleEnjoy Munit with Mule
Enjoy Munit with MuleBui Kiet
 
Junit in mule demo
Junit in mule demoJunit in mule demo
Junit in mule demoSudha Ch
 
Munit junit test case
Munit junit test caseMunit junit test case
Munit junit test caseprudhvivreddy
 
Mocking with salesforce using Munit
Mocking with salesforce using MunitMocking with salesforce using Munit
Mocking with salesforce using MunitSon Nguyen
 
Jmeter interviewquestions
Jmeter interviewquestionsJmeter interviewquestions
Jmeter interviewquestionsgirichinna27
 
BITM3730 10-3.pptx
BITM3730 10-3.pptxBITM3730 10-3.pptx
BITM3730 10-3.pptxMattMarino13
 
Building Complex Business Processes 3.7
Building Complex Business Processes 3.7Building Complex Business Processes 3.7
Building Complex Business Processes 3.7StephenKardian
 
BITM3730 10-4.pptx
BITM3730 10-4.pptxBITM3730 10-4.pptx
BITM3730 10-4.pptxMattMarino13
 
Building React Applications with Redux
Building React Applications with ReduxBuilding React Applications with Redux
Building React Applications with ReduxFITC
 
BITM3730Week6.pptx
BITM3730Week6.pptxBITM3730Week6.pptx
BITM3730Week6.pptxMattMarino13
 

Similar to J unit (20)

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
 
Junit in mule demo
Junit in mule demo Junit in mule demo
Junit in mule demo
 
Enjoy Munit with Mule
Enjoy Munit with MuleEnjoy Munit with Mule
Enjoy Munit with Mule
 
Junit in mule demo
Junit in mule demoJunit in mule demo
Junit in mule demo
 
Munit junit test case
Munit junit test caseMunit junit test case
Munit junit test case
 
Mocking with salesforce using Munit
Mocking with salesforce using MunitMocking with salesforce using Munit
Mocking with salesforce using Munit
 
Spring batch
Spring batchSpring batch
Spring batch
 
How to use batch component
How to use batch componentHow to use batch component
How to use batch component
 
Salesforce asynchronous apex
Salesforce asynchronous apexSalesforce asynchronous apex
Salesforce asynchronous apex
 
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
 
JavaScript for real men
JavaScript for real menJavaScript for real men
JavaScript for real men
 
Jmeter interviewquestions
Jmeter interviewquestionsJmeter interviewquestions
Jmeter interviewquestions
 
Javascript
JavascriptJavascript
Javascript
 
BITM3730 10-3.pptx
BITM3730 10-3.pptxBITM3730 10-3.pptx
BITM3730 10-3.pptx
 
Building Complex Business Processes 3.7
Building Complex Business Processes 3.7Building Complex Business Processes 3.7
Building Complex Business Processes 3.7
 
BITM3730 10-4.pptx
BITM3730 10-4.pptxBITM3730 10-4.pptx
BITM3730 10-4.pptx
 
Building React Applications with Redux
Building React Applications with ReduxBuilding React Applications with Redux
Building React Applications with Redux
 
BITM3730Week6.pptx
BITM3730Week6.pptxBITM3730Week6.pptx
BITM3730Week6.pptx
 

More from Durga Prasad Kakarla (9)

Vm Component
Vm ComponentVm Component
Vm Component
 
Until Successful Component
Until Successful ComponentUntil Successful Component
Until Successful Component
 
Mule Message Properties Component
Mule Message Properties ComponentMule Message Properties Component
Mule Message Properties Component
 
For Each Component
For Each ComponentFor Each Component
For Each Component
 
Expression Filters
Expression FiltersExpression Filters
Expression Filters
 
Database Component
Database ComponentDatabase Component
Database Component
 
Quartz component
Quartz componentQuartz component
Quartz component
 
Choice component
Choice componentChoice component
Choice component
 
File component
File componentFile component
File component
 

Recently uploaded

Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024Neo4j
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksSoftradix Technologies
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraDeakin University
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptxLBM Solutions
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 

Recently uploaded (20)

DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other Frameworks
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning era
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping Elbows
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptx
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 

J unit

  • 1. JUnit Functional Test Cases By: Durga Prasad K 09-Dec-2015
  • 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. 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.
  • 4. 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:
  • 5.
  • 6. • 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.
  • 7. • 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); • • ---- • ---- • } •
  • 8. • 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.
  • 10.
  • 11. • Flow of execution 1. Trigger the service with xml request. 2. Processes the input request. 3. Create the processed request as customer in Salesforce.
  • 12. • 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); • • ---- • ---- • }
  • 13. • 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.
  • 14. 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.
  • 15. • 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.
  • 16. • 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) );
  • 17. • 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; • }
  • 18. • /** • * 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 • } • }
  • 19. • 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.
  • 20. • 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 ) );
  • 21. • 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);
  • 22. • // 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 • } • }
  • 23. 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