SlideShare une entreprise Scribd logo
1  sur  19
TDD, Unit Testing(Spring) &
      Code Coverage
         - Jahangir
(md.jahangir27@gmail.com)
What is TDD?
   Software development process.

   Test-first programming concepts.
Advantages
   Code quality

   Focus and better understanding of requirements

   Modular, loosely coupled code
Shortcomings
   TDD brings in a sense of confidence, but not in the cases when developer
    misunderstands the requirements.

   Bad written tests are hard to maintain. Tests need as much attention as the
    code itself if not more.
How to TDD with Spring?
   Basics don’t change.

   STEPS:

   Code to interface(e.g. StudentService) , then code the skeleton concrete
    implementation(e.g. StudentServiceImpl) without details. Say, we need to write a method
    which takes studentId and classId as arguments and returns a Boolean indicating whether
    the student is registered for a class. In this example, in the concrete implementation as a
    first step should just return false.

   Create your test class. – Add a test case.

   In the test method for above scenario: pass in a valid studentId who is registered to a
    class, you would assert for true, but it returns false. – Fail a test case.
How to TDD with Spring?
   Now, write some code in the class to pass the test case i.e. access the Student
    DAO to make sure given a valid studentId and classId, it returns true – Pass the
    test case.

   Consider the requirements once again like what should be returned if studentId
    passed is null or classId is null(assuming non-primitives are passed). – Write tests
    for these cases, fail again. Forces you to think from business/functional
    perspective.

   Make necessary changes to your implementation to handle these cases. –
    Refactoring.

   Repeat from 1st step again.
Useful Unit testing Annotations
   @RunWith(SpringJUnit4ClassRunner.class)

   @ContextConfiguration(context xml loaded from classpath)

                  or

   @ContextConfiguration(classes={StudentServiceImplTestConfig.class})

Best practice: Create as minimum number of beans as possible as it’s a unit
test case and shouldn’t hinder your CI(Continous Integration).
Sample Spring Unit test
//Reference from spring documentation

package com.example;

@RunWith(SpringJunit4ClassRunner.class)

@ContextConfiguration(classes=OrderServiceConfiguration.class, loader=AnnotationConfigContextLoader.class)

Public class OrderServiceTest{

@Autowired

Private OrderService orderService;

@Test

Public void testOrderService(){

//test the service.

}

}
Resolving Dependencies of beans not under
test
   Scenario: Assume there is a “StudentService” bean which we talked about
    and has a new requirement - when the students logins using the studentId,
    it needs to return class ids the student is registered.

   Desired output: If the studentId doesn’t exist, throw an error message
    saying “Student ID doesn’t exist”. Else, return the class ids.

   Dependency: Now, it has a dependency on a Student DAO to check whether
    studentID exists and if it does, get the class ids.

   Best practice: Write tests in isolation i.e. if we are testing StudentService,
    then test only StudentService and not StudentDao.
Mockito
   Mocks creation.

   Verification.

   Stubbing.
Simple Mockito flavor

   http://pastebin.com/v4qRNv17 -- Sample code.
Scenario

         public List<integer> getClassIds (Integer studentId) throws
InvalidStudentException{

                  if(studentId== null ||studentId.isEmpty()){

                            throw new InvalidStudentException(”Student ID is
empty, please enter it");

                  }

                  if(studentDao.checkValidStudent(studentId))

                         return
studentDao.getClassIdsByStudentId(studentId);

                  else

                            throw new InvalidUserException("Invalid student
ID");

         }
As we can see, there is dependency on DAO, we can mock DAO something like
below:

StudentDao mockStudentDao = Mockito.mock(StudentDao.class);

when(mockUserDao.checkValidStudent(”1234")).thenReturn(true);

List<Integer> listOfClassIds = new ArrayList<Integer>();

listOfClassIds.add(101);

listOfClassIds.add(102);

when(mockUserDao.getClassIdsByStudentId(”1234")).thenReturn(listOfClassId
s);
Test case
         @Test

         public void testClassIds(){

         List<Integer> listOfClassIds = new ArrayList<Integer>();

         listOfClassIds.add(101);

         listOfClassIds.add(102);

         Assert.assertEquals("Display class ids for a valid
student”,listOfClassIds, studentService.getClassIds(”1234"));

         } //Now this takes care of studentDao as it’s mocked.
Mock HTTP
Mocks for various HTTP related stuff:
http://static.springsource.org/spring/docs/3.0.x/api/org/springframework/mo
ck/web/
Code Coverage
   Measure of how much code is tested.

   Very useful when you didn’t start the project with TDD, but adding tests
    later. It gives you a measure of how effective your tests are in covering your
    code.
EclEmma
   Java code coverage tool for Eclipse.

   Drill-down of coverage to method level.

   Source high-lighting.
References
   http://blog.springsource.org/2011/06/21/spring-3-1-m2-testing-with-
    configuration-classes-and-profiles/

   http://blogs.msdn.com/b/wesdyer/archive/2007/12/07/musings-on-
    software-testing.aspx (Image reference)

   http://code.google.com/p/mockito/ (Mockito)

   http://www.eclemma.org/ (EclEmma)

   http://static.springsource.org/spring/docs/3.0.x/api/org/springframework/
    mock/web/

Contenu connexe

Tendances

Dev labs alliance top 20 basic java interview questions for sdet
Dev labs alliance top 20 basic java interview questions for sdetDev labs alliance top 20 basic java interview questions for sdet
Dev labs alliance top 20 basic java interview questions for sdetDevLabs Alliance
 
Testing Android applications with Maveryx
Testing Android applications with MaveryxTesting Android applications with Maveryx
Testing Android applications with MaveryxMaveryx
 
Testing Java applications with Maveryx
Testing Java applications with MaveryxTesting Java applications with Maveryx
Testing Java applications with MaveryxMaveryx
 
DevLabs Alliance Top 20 Software Testing Interview Questions for SDET - by De...
DevLabs Alliance Top 20 Software Testing Interview Questions for SDET - by De...DevLabs Alliance Top 20 Software Testing Interview Questions for SDET - by De...
DevLabs Alliance Top 20 Software Testing Interview Questions for SDET - by De...DevLabs Alliance
 
Junit and cactus
Junit and cactusJunit and cactus
Junit and cactusHimanshu
 
Top 20 cucumber interview questions for sdet
Top 20 cucumber interview questions for sdetTop 20 cucumber interview questions for sdet
Top 20 cucumber interview questions for sdetDevLabs Alliance
 
Top 20 Junit interview questions for sdet
Top 20 Junit interview questions for sdetTop 20 Junit interview questions for sdet
Top 20 Junit interview questions for sdetDevLabs Alliance
 
Mockito vs JMockit, battle of the mocking frameworks
Mockito vs JMockit, battle of the mocking frameworksMockito vs JMockit, battle of the mocking frameworks
Mockito vs JMockit, battle of the mocking frameworksEndranNL
 
DevLabs Alliance Top 50 Selenium Interview Questions for SDET
DevLabs Alliance Top 50 Selenium Interview Questions for SDETDevLabs Alliance Top 50 Selenium Interview Questions for SDET
DevLabs Alliance Top 50 Selenium Interview Questions for SDETDevLabs Alliance
 
Top 20 software testing interview questions for sdet
Top 20 software testing interview questions for sdetTop 20 software testing interview questions for sdet
Top 20 software testing interview questions for sdetDevLabs Alliance
 
OCA Java SE 8 Exam Chapter 6 Exceptions
OCA Java SE 8 Exam Chapter 6 ExceptionsOCA Java SE 8 Exam Chapter 6 Exceptions
OCA Java SE 8 Exam Chapter 6 Exceptionsİbrahim Kürce
 
Mastering Mock Objects - Advanced Unit Testing for Java
Mastering Mock Objects - Advanced Unit Testing for JavaMastering Mock Objects - Advanced Unit Testing for Java
Mastering Mock Objects - Advanced Unit Testing for JavaDenilson Nastacio
 

Tendances (20)

Creating your own exception
Creating your own exceptionCreating your own exception
Creating your own exception
 
Unit testing with java
Unit testing with javaUnit testing with java
Unit testing with java
 
Dev labs alliance top 20 basic java interview questions for sdet
Dev labs alliance top 20 basic java interview questions for sdetDev labs alliance top 20 basic java interview questions for sdet
Dev labs alliance top 20 basic java interview questions for sdet
 
Easy mock
Easy mockEasy mock
Easy mock
 
Unit Testing 101
Unit Testing 101Unit Testing 101
Unit Testing 101
 
JUnit 5
JUnit 5JUnit 5
JUnit 5
 
Testing Android applications with Maveryx
Testing Android applications with MaveryxTesting Android applications with Maveryx
Testing Android applications with Maveryx
 
Testing Java applications with Maveryx
Testing Java applications with MaveryxTesting Java applications with Maveryx
Testing Java applications with Maveryx
 
Java Programming - 05 access control in java
Java Programming - 05 access control in javaJava Programming - 05 access control in java
Java Programming - 05 access control in java
 
DevLabs Alliance Top 20 Software Testing Interview Questions for SDET - by De...
DevLabs Alliance Top 20 Software Testing Interview Questions for SDET - by De...DevLabs Alliance Top 20 Software Testing Interview Questions for SDET - by De...
DevLabs Alliance Top 20 Software Testing Interview Questions for SDET - by De...
 
EasyMock for Java
EasyMock for JavaEasyMock for Java
EasyMock for Java
 
Junit and cactus
Junit and cactusJunit and cactus
Junit and cactus
 
Top 20 cucumber interview questions for sdet
Top 20 cucumber interview questions for sdetTop 20 cucumber interview questions for sdet
Top 20 cucumber interview questions for sdet
 
Top 20 Junit interview questions for sdet
Top 20 Junit interview questions for sdetTop 20 Junit interview questions for sdet
Top 20 Junit interview questions for sdet
 
Mockito vs JMockit, battle of the mocking frameworks
Mockito vs JMockit, battle of the mocking frameworksMockito vs JMockit, battle of the mocking frameworks
Mockito vs JMockit, battle of the mocking frameworks
 
Auto testing!
Auto testing!Auto testing!
Auto testing!
 
DevLabs Alliance Top 50 Selenium Interview Questions for SDET
DevLabs Alliance Top 50 Selenium Interview Questions for SDETDevLabs Alliance Top 50 Selenium Interview Questions for SDET
DevLabs Alliance Top 50 Selenium Interview Questions for SDET
 
Top 20 software testing interview questions for sdet
Top 20 software testing interview questions for sdetTop 20 software testing interview questions for sdet
Top 20 software testing interview questions for sdet
 
OCA Java SE 8 Exam Chapter 6 Exceptions
OCA Java SE 8 Exam Chapter 6 ExceptionsOCA Java SE 8 Exam Chapter 6 Exceptions
OCA Java SE 8 Exam Chapter 6 Exceptions
 
Mastering Mock Objects - Advanced Unit Testing for Java
Mastering Mock Objects - Advanced Unit Testing for JavaMastering Mock Objects - Advanced Unit Testing for Java
Mastering Mock Objects - Advanced Unit Testing for Java
 

Similaire à TDD-UnitTestingSpring-CodeCov

We Are All Testers Now: The Testing Pyramid and Front-End Development
We Are All Testers Now: The Testing Pyramid and Front-End DevelopmentWe Are All Testers Now: The Testing Pyramid and Front-End Development
We Are All Testers Now: The Testing Pyramid and Front-End DevelopmentAll Things Open
 
TDD step patterns
TDD step patternsTDD step patterns
TDD step patternseduardomg23
 
Iterative architecture
Iterative architectureIterative architecture
Iterative architectureJoshuaRizzo4
 
Intro To Unit and integration Testing
Intro To Unit and integration TestingIntro To Unit and integration Testing
Intro To Unit and integration TestingPaul Churchward
 
Test & behavior driven development
Test & behavior driven developmentTest & behavior driven development
Test & behavior driven developmentTristan Libersat
 
Lecture 4_Java Method-constructor_imp_keywords
Lecture   4_Java Method-constructor_imp_keywordsLecture   4_Java Method-constructor_imp_keywords
Lecture 4_Java Method-constructor_imp_keywordsmanish kumar
 
Working Effectively With Legacy Code
Working Effectively With Legacy CodeWorking Effectively With Legacy Code
Working Effectively With Legacy CodeNaresh Jain
 
Automation test
Automation testAutomation test
Automation testyuyijq
 
Sample Chapter of Practical Unit Testing with TestNG and Mockito
Sample Chapter of Practical Unit Testing with TestNG and MockitoSample Chapter of Practical Unit Testing with TestNG and Mockito
Sample Chapter of Practical Unit Testing with TestNG and MockitoTomek Kaczanowski
 
Selenium my sql and junit user guide
Selenium my sql and junit user guideSelenium my sql and junit user guide
Selenium my sql and junit user guideFahad Shiekh
 
Unit testing (workshop)
Unit testing (workshop)Unit testing (workshop)
Unit testing (workshop)Foyzul Karim
 
Not your father's tests
Not your father's testsNot your father's tests
Not your father's testsSean P. Floyd
 
Introduction of Object Oriented Programming Language using Java. .pptx
Introduction of Object Oriented Programming Language using Java. .pptxIntroduction of Object Oriented Programming Language using Java. .pptx
Introduction of Object Oriented Programming Language using Java. .pptxPoonam60376
 
03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slotsmha4
 
03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slotsmha4
 
21 ijaprr vol1-3-12-17juni
21 ijaprr vol1-3-12-17juni21 ijaprr vol1-3-12-17juni
21 ijaprr vol1-3-12-17juniijaprr_editor
 
L11a Create the Student class derived from the Person class- A student.docx
L11a Create the Student class derived from the Person class- A student.docxL11a Create the Student class derived from the Person class- A student.docx
L11a Create the Student class derived from the Person class- A student.docxJacob6ALMcDonaldu
 

Similaire à TDD-UnitTestingSpring-CodeCov (20)

We Are All Testers Now: The Testing Pyramid and Front-End Development
We Are All Testers Now: The Testing Pyramid and Front-End DevelopmentWe Are All Testers Now: The Testing Pyramid and Front-End Development
We Are All Testers Now: The Testing Pyramid and Front-End Development
 
TDD step patterns
TDD step patternsTDD step patterns
TDD step patterns
 
Iterative architecture
Iterative architectureIterative architecture
Iterative architecture
 
Intro To Unit and integration Testing
Intro To Unit and integration TestingIntro To Unit and integration Testing
Intro To Unit and integration Testing
 
Linq
LinqLinq
Linq
 
Test & behavior driven development
Test & behavior driven developmentTest & behavior driven development
Test & behavior driven development
 
Lecture 4_Java Method-constructor_imp_keywords
Lecture   4_Java Method-constructor_imp_keywordsLecture   4_Java Method-constructor_imp_keywords
Lecture 4_Java Method-constructor_imp_keywords
 
Working Effectively With Legacy Code
Working Effectively With Legacy CodeWorking Effectively With Legacy Code
Working Effectively With Legacy Code
 
Automation test
Automation testAutomation test
Automation test
 
Clean tests good tests
Clean tests   good testsClean tests   good tests
Clean tests good tests
 
Sample Chapter of Practical Unit Testing with TestNG and Mockito
Sample Chapter of Practical Unit Testing with TestNG and MockitoSample Chapter of Practical Unit Testing with TestNG and Mockito
Sample Chapter of Practical Unit Testing with TestNG and Mockito
 
Selenium my sql and junit user guide
Selenium my sql and junit user guideSelenium my sql and junit user guide
Selenium my sql and junit user guide
 
Methods in Java
Methods in JavaMethods in Java
Methods in Java
 
Unit testing (workshop)
Unit testing (workshop)Unit testing (workshop)
Unit testing (workshop)
 
Not your father's tests
Not your father's testsNot your father's tests
Not your father's tests
 
Introduction of Object Oriented Programming Language using Java. .pptx
Introduction of Object Oriented Programming Language using Java. .pptxIntroduction of Object Oriented Programming Language using Java. .pptx
Introduction of Object Oriented Programming Language using Java. .pptx
 
03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots
 
03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots
 
21 ijaprr vol1-3-12-17juni
21 ijaprr vol1-3-12-17juni21 ijaprr vol1-3-12-17juni
21 ijaprr vol1-3-12-17juni
 
L11a Create the Student class derived from the Person class- A student.docx
L11a Create the Student class derived from the Person class- A student.docxL11a Create the Student class derived from the Person class- A student.docx
L11a Create the Student class derived from the Person class- A student.docx
 

Dernier

The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
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
 
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 2024The Digital Insurer
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
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 Scriptwesley chun
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 

Dernier (20)

The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.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
 
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
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
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
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 

TDD-UnitTestingSpring-CodeCov

  • 1. TDD, Unit Testing(Spring) & Code Coverage - Jahangir (md.jahangir27@gmail.com)
  • 2. What is TDD?  Software development process.  Test-first programming concepts.
  • 3.
  • 4. Advantages  Code quality  Focus and better understanding of requirements  Modular, loosely coupled code
  • 5. Shortcomings  TDD brings in a sense of confidence, but not in the cases when developer misunderstands the requirements.  Bad written tests are hard to maintain. Tests need as much attention as the code itself if not more.
  • 6. How to TDD with Spring?  Basics don’t change.  STEPS:  Code to interface(e.g. StudentService) , then code the skeleton concrete implementation(e.g. StudentServiceImpl) without details. Say, we need to write a method which takes studentId and classId as arguments and returns a Boolean indicating whether the student is registered for a class. In this example, in the concrete implementation as a first step should just return false.  Create your test class. – Add a test case.  In the test method for above scenario: pass in a valid studentId who is registered to a class, you would assert for true, but it returns false. – Fail a test case.
  • 7. How to TDD with Spring?  Now, write some code in the class to pass the test case i.e. access the Student DAO to make sure given a valid studentId and classId, it returns true – Pass the test case.  Consider the requirements once again like what should be returned if studentId passed is null or classId is null(assuming non-primitives are passed). – Write tests for these cases, fail again. Forces you to think from business/functional perspective.  Make necessary changes to your implementation to handle these cases. – Refactoring.  Repeat from 1st step again.
  • 8. Useful Unit testing Annotations  @RunWith(SpringJUnit4ClassRunner.class)  @ContextConfiguration(context xml loaded from classpath) or  @ContextConfiguration(classes={StudentServiceImplTestConfig.class}) Best practice: Create as minimum number of beans as possible as it’s a unit test case and shouldn’t hinder your CI(Continous Integration).
  • 9. Sample Spring Unit test //Reference from spring documentation package com.example; @RunWith(SpringJunit4ClassRunner.class) @ContextConfiguration(classes=OrderServiceConfiguration.class, loader=AnnotationConfigContextLoader.class) Public class OrderServiceTest{ @Autowired Private OrderService orderService; @Test Public void testOrderService(){ //test the service. } }
  • 10. Resolving Dependencies of beans not under test  Scenario: Assume there is a “StudentService” bean which we talked about and has a new requirement - when the students logins using the studentId, it needs to return class ids the student is registered.  Desired output: If the studentId doesn’t exist, throw an error message saying “Student ID doesn’t exist”. Else, return the class ids.  Dependency: Now, it has a dependency on a Student DAO to check whether studentID exists and if it does, get the class ids.  Best practice: Write tests in isolation i.e. if we are testing StudentService, then test only StudentService and not StudentDao.
  • 11. Mockito  Mocks creation.  Verification.  Stubbing.
  • 12. Simple Mockito flavor  http://pastebin.com/v4qRNv17 -- Sample code.
  • 13. Scenario public List<integer> getClassIds (Integer studentId) throws InvalidStudentException{ if(studentId== null ||studentId.isEmpty()){ throw new InvalidStudentException(”Student ID is empty, please enter it"); } if(studentDao.checkValidStudent(studentId)) return studentDao.getClassIdsByStudentId(studentId); else throw new InvalidUserException("Invalid student ID"); }
  • 14. As we can see, there is dependency on DAO, we can mock DAO something like below: StudentDao mockStudentDao = Mockito.mock(StudentDao.class); when(mockUserDao.checkValidStudent(”1234")).thenReturn(true); List<Integer> listOfClassIds = new ArrayList<Integer>(); listOfClassIds.add(101); listOfClassIds.add(102); when(mockUserDao.getClassIdsByStudentId(”1234")).thenReturn(listOfClassId s);
  • 15. Test case @Test public void testClassIds(){ List<Integer> listOfClassIds = new ArrayList<Integer>(); listOfClassIds.add(101); listOfClassIds.add(102); Assert.assertEquals("Display class ids for a valid student”,listOfClassIds, studentService.getClassIds(”1234")); } //Now this takes care of studentDao as it’s mocked.
  • 16. Mock HTTP Mocks for various HTTP related stuff: http://static.springsource.org/spring/docs/3.0.x/api/org/springframework/mo ck/web/
  • 17. Code Coverage  Measure of how much code is tested.  Very useful when you didn’t start the project with TDD, but adding tests later. It gives you a measure of how effective your tests are in covering your code.
  • 18. EclEmma  Java code coverage tool for Eclipse.  Drill-down of coverage to method level.  Source high-lighting.
  • 19. References  http://blog.springsource.org/2011/06/21/spring-3-1-m2-testing-with- configuration-classes-and-profiles/  http://blogs.msdn.com/b/wesdyer/archive/2007/12/07/musings-on- software-testing.aspx (Image reference)  http://code.google.com/p/mockito/ (Mockito)  http://www.eclemma.org/ (EclEmma)  http://static.springsource.org/spring/docs/3.0.x/api/org/springframework/ mock/web/