SlideShare a Scribd company logo
An Introduction to JUnitAnimesh Kumar
Toyota2Impetus Confidentialhttp://blog.crisp.se/henrikkniberg/2010/03/16/1268757660000.htmlToyota’s Prius exampleA defect found in the production phase is about 50 times more expensive than if it is found during prototyping. If the defect is found after production it will be about 1,000 – 10,000 times more expensiveReality turned out to be worse, a lot worse! Toyota’s problems with the Prius braking systems is costing them over $2 000 000 000 (2 billion!) to fix because of all the recalls and lost sales. “Toyota announced that a glitch with the software program that controls the vehicle's anti-lock braking system was to blame".
Why write tests?Write a lot of code, and one day something will stopworking!Fixing a bug is easy, but how about pinning it down? You never know where the ripples of your fixes can go.Are you sure the demon is dead?  3Impetus Confidential
Test Driven DevelopmentAn evolutionary approach to development where first you write a Test and then add Functionality to pass the test. Image courtesy: http://en.wikipedia.org/wiki/Test-driven_development4Impetus Confidential
What is Unit Testing?A Unit Test is a procedure to validate a single Functionality of an application. One Functionality  One Unit TestUnit Tests are automated and self-checked. They run in isolation of each other.They do NOT depend on or connect to external resources, like DB, Network etc.They can run in any order and even parallel to each other and that will be fine. 5Impetus Confidential
What do we get?Obviously, we get tests to validate the functionalities, but that’s not all…One part of the program is isolated from others, i.e. proper separation of concerns. An ecology to foster Interface/Contract approached programming. Interfaces are documented. Refactoring made smooth like butter lathered floor. Quick bug identification.6Impetus Confidential
JUnit – An introductionJUnit is a unit testing framework for the java programming language. It comes from the family of unit testing frameworks, collectively called xUnit, where ‘x’ stands for the programming language, e.g. CPPUnit, JSUnit, PHPUnit, PyUnit, RUnit etc. 	Kent Beck and Erich Gamma originally wrote this framework for ‘smalltalk’, and it was called SUnit. Later it rippled into other languages. 7Impetus Confidential
Why choose JUnit?Of course there are many tools like JUnit, but none like it. JUnit is simple and elegant. JUnit checks its own results and provide immediate customized feedback. JUnit is hierarchal. JUnit has the widest IDE support, Eclipse, NetBeans, IntelliJ IDEA … you name it.JUnit is recognized by popular build tools like, ant, maven etc.And… it’s free.  8Impetus Confidential
Design of JUnit9Impetus Confidentialjunit.framework.TestCase is the abstract command class which you subclass into your Test Classes.
junit.framework.TestSuite is a composite of other tests, either TestCaseor TestSuite. This behavior helps you create hierarchal tests with depth control. Design of JUnit10Impetus ConfidentialImage Courtesy: JUnit: A Cook’s Tour
Write a test caseDefine a subclass of junit.framework.TestCasepublic class CalculatorTest extends TestCase {}Define one or more testXXX() methods that can perform the tests and assert expected results. public void testAddition () {	Calculator calc = new Calculator();int expected = 25;int result = calc.add (10, 15);assertEquals (result, expected); // asserting}11Impetus Confidential
Write a test caseOverride setUp() method to perform initialization.@Overrideprotected void setUp () {	// Initialize anything, like	calc = new Calculator();}Override tearDown() method to clean up.@Overrideprotected void tearDown () {	// Clean up, like	calc = null;}12Impetus Confidential
Asserting expectationsassertEquals (expected, actual) assertEquals (message, expected, actual) assertEquals (expected, actual, delta)assertEquals (message, expected, actual, delta)  assertFalse ((message)condition) Assert(Not)Null (object) Assert(Not)Null (message, object) Assert(Not)Same (expected, actual) Assert(Not)Same (message, expected, actual) assertTrue ((message), condition)13Impetus Confidential
Failure?JUnit uses the term failure for a test that fails expectedly.That isAn assertion was not valid  or A fail() was encountered. 14Impetus Confidential
Write a test casepublic class CalculatorTest extends TestCase {	// initialize	protected void setUp ()...			Spublic void testAddition ()...  		T1	public void testSubtraction ()...		T2	public void testMultiplication ()...		T3	// clean up	protected void tearDownUp ()...		C }Execution will be S T1 C, S T2 C, S T3 Cin any order. 15Impetus Confidential
Write a test suiteWrite a class with a static method suite() that creates a junit.framework.TestSuitecontaining all the Tests. public class AllTests {	public static Test suite() {TestSuite suite = new TestSuite();suite.addTestSuite(<test-1>.class);suite.addTestSuite(<test-2>.class);		return suite;	}}16Impetus Confidential
Run your testsYou can either run TestCase or TestSuite instances.A TestSuite will automatically run all its registered TestCase instances. All public testXXX() methods of a TestCase will be executed. But there is no guarantee of the order. 17Impetus Confidential
Run your testsJUnit comes with TestRunners that run your tests and immediately provide you with feedbacks, errors, and status of completion. JUnit has Textual and Graphical test runners. Textual Runner >> java junit.textui.TestRunnerAllTestsor,junit.textui.TestRunner.run(AllTests.class);Graphical Runner >> java junit.swingui.TestRunnerAllTestsor,junit.swingui.TestRunner.run(AllTests.class);IDE like Eclipse, NetBeans “Run as JUnit”18Impetus Confidential
Test maintenance19Impetus ConfidentialCreate 2 separate directories for source and testcodes.
Mirror source package structure into test.
Define a TestSuite for each java package that would contain all TestCase instances for this package. This will create a hierarchy of Tests. > com		      	-> impetus	      	- AllTests> Book	      	- BookTests. AddBook	    - AddBookTest. DeleteBook	    - DeleteBookTest. ListBooks	    - ListBooksTest> Library	- LibraryTests> User		- UserTests
MocksMocking is a way to deal with third-party dependencies inside TestCase. Mocks create FAKE objects to mock a contract behavior. Mocks help make tests more unitary. 20Impetus Confidential
EasyMockEasyMock is an open-source java library to help you create Mock Objects.Flow:  Expect => Replay => VerifyuserService = EasyMock.createMock(IUserService.class);		1User user = ... //EasyMock	.expect (userService.isRegisteredUser(user))			2	.andReturn (true);						3EasyMock.replay(userService);					4assertTrue(userService.isRegisteredUser(user));		5Modes: Strict and Nice21Impetus Confidential
JUnit and Eclipse22Impetus Confidential
JUnit and build tools23Impetus ConfidentialApache Maven> mvn test> mvn -Dtest=MyTestCase,MyOtherTestCase testApache Ant<junitprintsummary="yes" haltonfailure="yes">  <test name="my.test.TestCase"/></junit><junitprintsummary="yes" haltonfailure="yes">  <batchtest fork="yes" todir="${reports.tests}">    <fileset dir="${src.tests}">      <include name="**/*Test*.java"/>      <exclude name="**/AllTests.java"/>    </fileset>  </batchtest></junit>
Side effects – good or bad?24Impetus ConfidentialDesigned to call methods.This works great for methods that just return resultsMethods that change the state of the object could turn out to be tricky to testDifficult to unit test GUI codeEncourages “functional” style of codingThis can be a good thing
How to approach?25Impetus ConfidentialTest a little, Code a little, Test a little, Code a little … doesn’t it rhyme? ;) Write tests to validate functionality, not functions. If tempted to write System.out.println() to debug something, better write a test for it. If a bug is found, write a test to expose the bug.

More Related Content

PDF
PPTX
JUnit- A Unit Testing Framework
PPT
05 junit
PPTX
Java Unit Testing
PPSX
PPTX
Introduction to JUnit
PPS
JUnit Presentation
PPT
JUnit- A Unit Testing Framework
05 junit
Java Unit Testing
Introduction to JUnit
JUnit Presentation

What's hot (20)

PDF
JUnit & Mockito, first steps
PDF
Unit testing with JUnit
PDF
Unit testing with JUnit
PPTX
Unit Testing And Mocking
ODP
Beginners - Get Started With Unit Testing in .NET
PDF
Mocking in Java with Mockito
PPTX
PDF
Unit Testing in Angular
PPT
PPTX
An Introduction to Unit Testing
PDF
Java 8 Lambda Expressions
PPTX
Selenium TestNG
PPTX
Unit testing
PDF
Unit Testing
PDF
Workshop unit test
PPT
Unit testing with java
PPTX
Unit Testing
PPT
PDF
An Introduction to JUnit 5 and how to use it with Spring boot tests and Mockito
PDF
Java - Exception Handling Concepts
JUnit & Mockito, first steps
Unit testing with JUnit
Unit testing with JUnit
Unit Testing And Mocking
Beginners - Get Started With Unit Testing in .NET
Mocking in Java with Mockito
Unit Testing in Angular
An Introduction to Unit Testing
Java 8 Lambda Expressions
Selenium TestNG
Unit testing
Unit Testing
Workshop unit test
Unit testing with java
Unit Testing
An Introduction to JUnit 5 and how to use it with Spring boot tests and Mockito
Java - Exception Handling Concepts
Ad

Similar to JUNit Presentation (20)

PPTX
Testing your code
PPTX
Testing with Junit4
PPTX
TDD - Unit Testing
PDF
Introduction to test automation in java and php
PDF
JUnit with_mocking
PDF
31b - JUnit and Mockito.pdf
PPTX
JUnit 5 - from Lambda to Alpha and beyond
PPTX
Test-Driven Development
PPTX
Testing your code
PDF
JUnit Testing Framework A Complete Guide.pdf
PDF
JUnit Testing Framework A Complete Guide.pdf
PPTX
8-testing.pptx
PDF
Android Test Driven Development & Android Unit Testing
PDF
junit-160729073220 eclipse software testing.pdf
PPTX
JUnit Test Case With Processminer modules.pptx
PPTX
The Test way
PPTX
Write tests, please
PPTX
SE2018_Lec 20_ Test-Driven Development (TDD)
ODP
Effective unit testing
Testing your code
Testing with Junit4
TDD - Unit Testing
Introduction to test automation in java and php
JUnit with_mocking
31b - JUnit and Mockito.pdf
JUnit 5 - from Lambda to Alpha and beyond
Test-Driven Development
Testing your code
JUnit Testing Framework A Complete Guide.pdf
JUnit Testing Framework A Complete Guide.pdf
8-testing.pptx
Android Test Driven Development & Android Unit Testing
junit-160729073220 eclipse software testing.pdf
JUnit Test Case With Processminer modules.pptx
The Test way
Write tests, please
SE2018_Lec 20_ Test-Driven Development (TDD)
Effective unit testing
Ad

Recently uploaded (20)

PDF
OneRead_20250728_1807.pdfbdjsajaajjajajsjsj
PDF
Want to Fly Like an Eagle - Leave the Chickens Behind.pdf
PDF
⚡ Prepping for grid failure_ 6 Must-Haves to Survive Blackout!.pdf
PPTX
Commmunication in Todays world- Principles and Barriers
PDF
Top 10 Visionary Entrepreneurs to Watch in 2025
PDF
Lesson 4 Education for Better Work. Evaluate your training options.
PDF
SEX-GENDER-AND-SEXUALITY-LESSON-1-M (2).pdf
PDF
Quiet Wins: Why the Silent Fish Survives.pdf
DOCX
Boost your energy levels and Shred Weight
PDF
PLAYLISTS DEI MEGAMIX E DEEJAY PARADE DAL 1991 AL 2004 SU RADIO DEEJAY
PDF
The Blogs_ Humanity Beyond All Differences _ Andy Blumenthal _ The Times of I...
PPTX
Emotional Intelligence- Importance and Applicability
PDF
Dominate Her Mind – Make Women Chase, Lust, & Submit
PPTX
Unlocking Success Through the Relentless Power of Grit
PDF
Why is mindset more important than motivation.pdf
PDF
Anxiety Awareness Journal One Week Preview
PPT
Lesson From Geese! Understanding Teamwork
PPTX
THEORIES-PSYCH-3.pptx theory of Abraham Maslow
PPTX
show1- motivational ispiring positive thinking
DOCX
Paulo Tuynmam: Nine Timeless Anchors of Authentic Leadership
OneRead_20250728_1807.pdfbdjsajaajjajajsjsj
Want to Fly Like an Eagle - Leave the Chickens Behind.pdf
⚡ Prepping for grid failure_ 6 Must-Haves to Survive Blackout!.pdf
Commmunication in Todays world- Principles and Barriers
Top 10 Visionary Entrepreneurs to Watch in 2025
Lesson 4 Education for Better Work. Evaluate your training options.
SEX-GENDER-AND-SEXUALITY-LESSON-1-M (2).pdf
Quiet Wins: Why the Silent Fish Survives.pdf
Boost your energy levels and Shred Weight
PLAYLISTS DEI MEGAMIX E DEEJAY PARADE DAL 1991 AL 2004 SU RADIO DEEJAY
The Blogs_ Humanity Beyond All Differences _ Andy Blumenthal _ The Times of I...
Emotional Intelligence- Importance and Applicability
Dominate Her Mind – Make Women Chase, Lust, & Submit
Unlocking Success Through the Relentless Power of Grit
Why is mindset more important than motivation.pdf
Anxiety Awareness Journal One Week Preview
Lesson From Geese! Understanding Teamwork
THEORIES-PSYCH-3.pptx theory of Abraham Maslow
show1- motivational ispiring positive thinking
Paulo Tuynmam: Nine Timeless Anchors of Authentic Leadership

JUNit Presentation

  • 1. An Introduction to JUnitAnimesh Kumar
  • 2. Toyota2Impetus Confidentialhttp://blog.crisp.se/henrikkniberg/2010/03/16/1268757660000.htmlToyota’s Prius exampleA defect found in the production phase is about 50 times more expensive than if it is found during prototyping. If the defect is found after production it will be about 1,000 – 10,000 times more expensiveReality turned out to be worse, a lot worse! Toyota’s problems with the Prius braking systems is costing them over $2 000 000 000 (2 billion!) to fix because of all the recalls and lost sales. “Toyota announced that a glitch with the software program that controls the vehicle's anti-lock braking system was to blame".
  • 3. Why write tests?Write a lot of code, and one day something will stopworking!Fixing a bug is easy, but how about pinning it down? You never know where the ripples of your fixes can go.Are you sure the demon is dead? 3Impetus Confidential
  • 4. Test Driven DevelopmentAn evolutionary approach to development where first you write a Test and then add Functionality to pass the test. Image courtesy: http://en.wikipedia.org/wiki/Test-driven_development4Impetus Confidential
  • 5. What is Unit Testing?A Unit Test is a procedure to validate a single Functionality of an application. One Functionality  One Unit TestUnit Tests are automated and self-checked. They run in isolation of each other.They do NOT depend on or connect to external resources, like DB, Network etc.They can run in any order and even parallel to each other and that will be fine. 5Impetus Confidential
  • 6. What do we get?Obviously, we get tests to validate the functionalities, but that’s not all…One part of the program is isolated from others, i.e. proper separation of concerns. An ecology to foster Interface/Contract approached programming. Interfaces are documented. Refactoring made smooth like butter lathered floor. Quick bug identification.6Impetus Confidential
  • 7. JUnit – An introductionJUnit is a unit testing framework for the java programming language. It comes from the family of unit testing frameworks, collectively called xUnit, where ‘x’ stands for the programming language, e.g. CPPUnit, JSUnit, PHPUnit, PyUnit, RUnit etc. Kent Beck and Erich Gamma originally wrote this framework for ‘smalltalk’, and it was called SUnit. Later it rippled into other languages. 7Impetus Confidential
  • 8. Why choose JUnit?Of course there are many tools like JUnit, but none like it. JUnit is simple and elegant. JUnit checks its own results and provide immediate customized feedback. JUnit is hierarchal. JUnit has the widest IDE support, Eclipse, NetBeans, IntelliJ IDEA … you name it.JUnit is recognized by popular build tools like, ant, maven etc.And… it’s free.  8Impetus Confidential
  • 9. Design of JUnit9Impetus Confidentialjunit.framework.TestCase is the abstract command class which you subclass into your Test Classes.
  • 10. junit.framework.TestSuite is a composite of other tests, either TestCaseor TestSuite. This behavior helps you create hierarchal tests with depth control. Design of JUnit10Impetus ConfidentialImage Courtesy: JUnit: A Cook’s Tour
  • 11. Write a test caseDefine a subclass of junit.framework.TestCasepublic class CalculatorTest extends TestCase {}Define one or more testXXX() methods that can perform the tests and assert expected results. public void testAddition () { Calculator calc = new Calculator();int expected = 25;int result = calc.add (10, 15);assertEquals (result, expected); // asserting}11Impetus Confidential
  • 12. Write a test caseOverride setUp() method to perform initialization.@Overrideprotected void setUp () { // Initialize anything, like calc = new Calculator();}Override tearDown() method to clean up.@Overrideprotected void tearDown () { // Clean up, like calc = null;}12Impetus Confidential
  • 13. Asserting expectationsassertEquals (expected, actual) assertEquals (message, expected, actual) assertEquals (expected, actual, delta)assertEquals (message, expected, actual, delta) assertFalse ((message)condition) Assert(Not)Null (object) Assert(Not)Null (message, object) Assert(Not)Same (expected, actual) Assert(Not)Same (message, expected, actual) assertTrue ((message), condition)13Impetus Confidential
  • 14. Failure?JUnit uses the term failure for a test that fails expectedly.That isAn assertion was not valid or A fail() was encountered. 14Impetus Confidential
  • 15. Write a test casepublic class CalculatorTest extends TestCase { // initialize protected void setUp ()... Spublic void testAddition ()... T1 public void testSubtraction ()... T2 public void testMultiplication ()... T3 // clean up protected void tearDownUp ()... C }Execution will be S T1 C, S T2 C, S T3 Cin any order. 15Impetus Confidential
  • 16. Write a test suiteWrite a class with a static method suite() that creates a junit.framework.TestSuitecontaining all the Tests. public class AllTests { public static Test suite() {TestSuite suite = new TestSuite();suite.addTestSuite(<test-1>.class);suite.addTestSuite(<test-2>.class); return suite; }}16Impetus Confidential
  • 17. Run your testsYou can either run TestCase or TestSuite instances.A TestSuite will automatically run all its registered TestCase instances. All public testXXX() methods of a TestCase will be executed. But there is no guarantee of the order. 17Impetus Confidential
  • 18. Run your testsJUnit comes with TestRunners that run your tests and immediately provide you with feedbacks, errors, and status of completion. JUnit has Textual and Graphical test runners. Textual Runner >> java junit.textui.TestRunnerAllTestsor,junit.textui.TestRunner.run(AllTests.class);Graphical Runner >> java junit.swingui.TestRunnerAllTestsor,junit.swingui.TestRunner.run(AllTests.class);IDE like Eclipse, NetBeans “Run as JUnit”18Impetus Confidential
  • 19. Test maintenance19Impetus ConfidentialCreate 2 separate directories for source and testcodes.
  • 20. Mirror source package structure into test.
  • 21. Define a TestSuite for each java package that would contain all TestCase instances for this package. This will create a hierarchy of Tests. > com -> impetus - AllTests> Book - BookTests. AddBook - AddBookTest. DeleteBook - DeleteBookTest. ListBooks - ListBooksTest> Library - LibraryTests> User - UserTests
  • 22. MocksMocking is a way to deal with third-party dependencies inside TestCase. Mocks create FAKE objects to mock a contract behavior. Mocks help make tests more unitary. 20Impetus Confidential
  • 23. EasyMockEasyMock is an open-source java library to help you create Mock Objects.Flow: Expect => Replay => VerifyuserService = EasyMock.createMock(IUserService.class); 1User user = ... //EasyMock .expect (userService.isRegisteredUser(user)) 2 .andReturn (true); 3EasyMock.replay(userService); 4assertTrue(userService.isRegisteredUser(user)); 5Modes: Strict and Nice21Impetus Confidential
  • 25. JUnit and build tools23Impetus ConfidentialApache Maven> mvn test> mvn -Dtest=MyTestCase,MyOtherTestCase testApache Ant<junitprintsummary="yes" haltonfailure="yes"> <test name="my.test.TestCase"/></junit><junitprintsummary="yes" haltonfailure="yes"> <batchtest fork="yes" todir="${reports.tests}"> <fileset dir="${src.tests}"> <include name="**/*Test*.java"/> <exclude name="**/AllTests.java"/> </fileset> </batchtest></junit>
  • 26. Side effects – good or bad?24Impetus ConfidentialDesigned to call methods.This works great for methods that just return resultsMethods that change the state of the object could turn out to be tricky to testDifficult to unit test GUI codeEncourages “functional” style of codingThis can be a good thing
  • 27. How to approach?25Impetus ConfidentialTest a little, Code a little, Test a little, Code a little … doesn’t it rhyme? ;) Write tests to validate functionality, not functions. If tempted to write System.out.println() to debug something, better write a test for it. If a bug is found, write a test to expose the bug.
  • 28. Resources26Impetus ConfidentialBook: Manning: JUnit in Actionhttp://www.junit.org/index.htmhttp://www.cs.umanitoba.ca/~eclipse/10-JUnit.pdfhttp://supportweb.cs.bham.ac.uk/documentation/tutorials/docsystem/build/tutorials/junit/junit.pdfhttp://junit.sourceforge.net/javadoc/junit/framework/

Editor's Notes

  • #3: Long hourswith stoned debuggers!
  • #4: Long hourswith stoned debuggers!
  • #5: Long hourswith stoned debuggers!
  • #6: Example of calculator!
  • #7: Example of calculator!
  • #8: Long hourswith stoned debuggers!
  • #9: Long hourswith stoned debuggers!
  • #10: Long hourswith stoned debuggers!
  • #11: Long hourswith stoned debuggers!
  • #12: Long hourswith stoned debuggers!
  • #13: Long hourswith stoned debuggers!
  • #14: Long hourswith stoned debuggers!
  • #15: Long hourswith stoned debuggers!
  • #16: Long hourswith stoned debuggers!
  • #17: Long hourswith stoned debuggers!
  • #18: Long hourswith stoned debuggers!
  • #19: Long hourswith stoned debuggers!
  • #20: Long hourswith stoned debuggers!
  • #21: Long hourswith stoned debuggers!
  • #22: Long hourswith stoned debuggers!
  • #23: Long hourswith stoned debuggers!
  • #24: Long hourswith stoned debuggers!
  • #25: Long hourswith stoned debuggers!
  • #26: Long hourswith stoned debuggers!
  • #27: Long hourswith stoned debuggers!