Published on

Published in: Technology
  • Be the first to comment

  • Be the first to like this

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide


  1. 1. TDD, Unit Testing(Spring) & Code Coverage - Jahangir(
  2. 2. What is TDD? Software development process. Test-first programming concepts.
  3. 3. Advantages Code quality Focus and better understanding of requirements Modular, loosely coupled code
  4. 4. 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.
  5. 5. 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.
  6. 6. 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.
  7. 7. 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 unittest case and shouldn’t hinder your CI(Continous Integration).
  8. 8. Sample Spring Unit test//Reference from spring documentationpackage com.example;@RunWith(SpringJunit4ClassRunner.class)@ContextConfiguration(classes=OrderServiceConfiguration.class, loader=AnnotationConfigContextLoader.class)Public class OrderServiceTest{@AutowiredPrivate OrderService orderService;@TestPublic void testOrderService(){//test the service.}}
  9. 9. Resolving Dependencies of beans not undertest 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.
  10. 10. Mockito Mocks creation. Verification. Stubbing.
  11. 11. Simple Mockito flavor -- Sample code.
  12. 12. Scenario public List<integer> getClassIds (Integer studentId) throwsInvalidStudentException{ if(studentId== null ||studentId.isEmpty()){ throw new InvalidStudentException(”Student ID isempty, please enter it"); } if(studentDao.checkValidStudent(studentId)) returnstudentDao.getClassIdsByStudentId(studentId); else throw new InvalidUserException("Invalid studentID"); }
  13. 13. As we can see, there is dependency on DAO, we can mock DAO something likebelow: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(listOfClassIds);
  14. 14. 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 validstudent”,listOfClassIds, studentService.getClassIds(”1234")); } //Now this takes care of studentDao as it’s mocked.
  15. 15. Mock HTTPMocks for various HTTP related stuff:
  16. 16. 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.
  17. 17. EclEmma Java code coverage tool for Eclipse. Drill-down of coverage to method level. Source high-lighting.
  18. 18. References configuration-classes-and-profiles/ software-testing.aspx (Image reference) (Mockito) (EclEmma) mock/web/