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

   Test-first programming concepts.
TDD-UnitTestingSpring-CodeCov
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/

More Related Content

PPTX
Unit Testing in Java
PDF
J unit a starter guide
PDF
Security Vulnerability Notice SE-2012-01-PUBLIC [Security vulnerabilities in ...
PDF
1z0-808-certification-questions-sample
PPT
JMockit
PPT
JMockit Framework Overview
ODP
Easymock Tutorial
ODP
Embrace Unit Testing
Unit Testing in Java
J unit a starter guide
Security Vulnerability Notice SE-2012-01-PUBLIC [Security vulnerabilities in ...
1z0-808-certification-questions-sample
JMockit
JMockit Framework Overview
Easymock Tutorial
Embrace Unit Testing

What's hot (20)

PDF
Creating your own exception
PPT
Unit testing with java
PPTX
Dev labs alliance top 20 basic java interview questions for sdet
PPTX
Easy mock
PDF
Unit Testing 101
PDF
PDF
Testing Android applications with Maveryx
PDF
Testing Java applications with Maveryx
PDF
Java Programming - 05 access control in java
PPTX
DevLabs Alliance Top 20 Software Testing Interview Questions for SDET - by De...
PPT
EasyMock for Java
PPTX
Junit and cactus
PPTX
Top 20 cucumber interview questions for sdet
PPTX
Top 20 Junit interview questions for sdet
PPTX
Mockito vs JMockit, battle of the mocking frameworks
PDF
Auto testing!
PPTX
DevLabs Alliance Top 50 Selenium Interview Questions for SDET
PPTX
Top 20 software testing interview questions for sdet
PPTX
OCA Java SE 8 Exam Chapter 6 Exceptions
ODP
Mastering Mock Objects - Advanced Unit Testing for Java
Creating your own exception
Unit testing with java
Dev labs alliance top 20 basic java interview questions for sdet
Easy mock
Unit Testing 101
Testing Android applications with Maveryx
Testing Java applications with Maveryx
Java Programming - 05 access control in java
DevLabs Alliance Top 20 Software Testing Interview Questions for SDET - by De...
EasyMock for Java
Junit and cactus
Top 20 cucumber interview questions for sdet
Top 20 Junit interview questions for sdet
Mockito vs JMockit, battle of the mocking frameworks
Auto testing!
DevLabs Alliance Top 50 Selenium Interview Questions for SDET
Top 20 software testing interview questions for sdet
OCA Java SE 8 Exam Chapter 6 Exceptions
Mastering Mock Objects - Advanced Unit Testing for Java
Ad

Similar to TDD-UnitTestingSpring-CodeCov (20)

PDF
Unit testing basic
PDF
Journey's diary developing a framework using tdd
PDF
Unit testing 101
PDF
Scrum Gathering 2012 Shanghai_工程实践与技术卓越分会场:how to write unit test for new cod...
PDF
Testing and TDD - KoJUG
KEY
Testing w-mocks
PPTX
Java Unit Test - JUnit
PPT
Solit 2012, TDD и отдельные аспекты тестирования в Java, Антонина Шафранская
PDF
An Introduction To Unit Testing and TDD
PDF
31b - JUnit and Mockito.pdf
PDF
How and what to unit test
PPTX
Testing Spring Applications
PDF
Make it test-driven with CDI!
PPT
Testing – With Mock Objects
PPTX
Advance unittest
PDF
Factorio crack FREE Download Latest Version 2025
PDF
Crack FREE Gta 5Download Latest Version 2025
PDF
One Deceptively Simple Question to Unlock Testability, Better Design, and TDD
PPTX
Junit mockito and PowerMock in Java
PPTX
Presentation
Unit testing basic
Journey's diary developing a framework using tdd
Unit testing 101
Scrum Gathering 2012 Shanghai_工程实践与技术卓越分会场:how to write unit test for new cod...
Testing and TDD - KoJUG
Testing w-mocks
Java Unit Test - JUnit
Solit 2012, TDD и отдельные аспекты тестирования в Java, Антонина Шафранская
An Introduction To Unit Testing and TDD
31b - JUnit and Mockito.pdf
How and what to unit test
Testing Spring Applications
Make it test-driven with CDI!
Testing – With Mock Objects
Advance unittest
Factorio crack FREE Download Latest Version 2025
Crack FREE Gta 5Download Latest Version 2025
One Deceptively Simple Question to Unlock Testability, Better Design, and TDD
Junit mockito and PowerMock in Java
Presentation
Ad

Recently uploaded (20)

PDF
Video forgery: An extensive analysis of inter-and intra-frame manipulation al...
PDF
NewMind AI Weekly Chronicles - August'25-Week II
PDF
Assigned Numbers - 2025 - Bluetooth® Document
PDF
MIND Revenue Release Quarter 2 2025 Press Release
PDF
gpt5_lecture_notes_comprehensive_20250812015547.pdf
PPTX
Machine Learning_overview_presentation.pptx
PDF
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
PDF
Approach and Philosophy of On baking technology
PPTX
1. Introduction to Computer Programming.pptx
PPTX
Programs and apps: productivity, graphics, security and other tools
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PPTX
A Presentation on Artificial Intelligence
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PDF
Machine learning based COVID-19 study performance prediction
PDF
Network Security Unit 5.pdf for BCA BBA.
PDF
Accuracy of neural networks in brain wave diagnosis of schizophrenia
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PDF
cuic standard and advanced reporting.pdf
PDF
Electronic commerce courselecture one. Pdf
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
Video forgery: An extensive analysis of inter-and intra-frame manipulation al...
NewMind AI Weekly Chronicles - August'25-Week II
Assigned Numbers - 2025 - Bluetooth® Document
MIND Revenue Release Quarter 2 2025 Press Release
gpt5_lecture_notes_comprehensive_20250812015547.pdf
Machine Learning_overview_presentation.pptx
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
Approach and Philosophy of On baking technology
1. Introduction to Computer Programming.pptx
Programs and apps: productivity, graphics, security and other tools
Per capita expenditure prediction using model stacking based on satellite ima...
A Presentation on Artificial Intelligence
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
Machine learning based COVID-19 study performance prediction
Network Security Unit 5.pdf for BCA BBA.
Accuracy of neural networks in brain wave diagnosis of schizophrenia
Agricultural_Statistics_at_a_Glance_2022_0.pdf
cuic standard and advanced reporting.pdf
Electronic commerce courselecture one. Pdf
Building Integrated photovoltaic BIPV_UPV.pdf

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