SlideShare a Scribd company logo
1 of 27
An Introduction to JUnit Animesh Kumar
Toyota 2 Impetus Confidential http://blog.crisp.se/henrikkniberg/2010/03/16/1268757660000.html Toyota’s Prius example A 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 expensive Reality 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?   3 Impetus Confidential
Test Driven Development An 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_development 4 Impetus Confidential
What is Unit Testing? A Unit Test is a procedure to validate a single Functionality of an application.  One Functionality  One Unit Test Unit 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.  5 Impetus 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. 6 Impetus Confidential
JUnit – An introduction JUnit 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.  7 Impetus 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.   8 Impetus Confidential
Design of JUnit 9 Impetus Confidential ,[object Object]
junit.framework.TestSuite is a composite of other tests, either TestCaseor TestSuite. This behavior helps you create hierarchal tests with depth control. ,[object Object]
Write a test case Define a subclass of junit.framework.TestCase public 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 } 11 Impetus Confidential
Write a test case Override setUp() method to perform initialization. @Override protected void setUp () { 	// Initialize anything, like 	calc = new Calculator(); } Override tearDown() method to clean up. @Override protected void tearDown () { 	// Clean up, like 	calc = null; } 12 Impetus Confidential
Asserting expectations assertEquals (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) 13 Impetus Confidential
Failure? JUnit uses the term failure for a test that fails expectedly.That is An assertion was not valid  or  A fail() was encountered.  14 Impetus Confidential
Write a test case public 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.  15 Impetus Confidential
Write a test suite Write 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; 	} } 16 Impetus Confidential
Run your tests You 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.  17 Impetus Confidential
Run your tests JUnit 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.TestRunnerAllTests or, junit.textui.TestRunner.run(AllTests.class); Graphical Runner  >> java junit.swingui.TestRunnerAllTests or, junit.swingui.TestRunner.run(AllTests.class); IDE like Eclipse, NetBeans “Run as JUnit” 18 Impetus Confidential
Test maintenance 19 Impetus Confidential ,[object Object]
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
Mocks Mocking 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.  20 Impetus Confidential
EasyMock EasyMock is an open-source java library to help you create Mock Objects. Flow:  Expect => Replay => Verify userService = EasyMock.createMock(IUserService.class);		1 User user = ... // EasyMock 	.expect (userService.isRegisteredUser(user))			2 	.andReturn (true);						3 EasyMock.replay(userService);					4 assertTrue(userService.isRegisteredUser(user));		5 Modes: Strict and Nice 21 Impetus Confidential
JUnit and Eclipse 22 Impetus Confidential
JUnit and build tools 23 Impetus Confidential Apache Maven > mvn test > mvn -Dtest=MyTestCase,MyOtherTestCase test Apache 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? 24 Impetus Confidential Designed to call methods. This works great for methods that just return results Methods that change the state of the object could turn out to be tricky to test Difficult to unit test GUI code Encourages “functional” style of coding This can be a good thing
How to approach? 25 Impetus Confidential Test 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

What's hot

TestNG Annotations in Selenium | Edureka
TestNG Annotations in Selenium | EdurekaTestNG Annotations in Selenium | Edureka
TestNG Annotations in Selenium | EdurekaEdureka!
 
Unit Testing And Mocking
Unit Testing And MockingUnit Testing And Mocking
Unit Testing And MockingJoe Wilson
 
Mocking in Java with Mockito
Mocking in Java with MockitoMocking in Java with Mockito
Mocking in Java with MockitoRichard Paul
 
JUnit & Mockito, first steps
JUnit & Mockito, first stepsJUnit & Mockito, first steps
JUnit & Mockito, first stepsRenato Primavera
 
Unit testing framework
Unit testing frameworkUnit testing framework
Unit testing frameworkIgor Vavrish
 
An Introduction to Unit Testing
An Introduction to Unit TestingAn Introduction to Unit Testing
An Introduction to Unit TestingJoe Tremblay
 
Unit Testing in Angular
Unit Testing in AngularUnit Testing in Angular
Unit Testing in AngularKnoldus Inc.
 
Testing with Spring: An Introduction
Testing with Spring: An IntroductionTesting with Spring: An Introduction
Testing with Spring: An IntroductionSam Brannen
 
Understanding Unit Testing
Understanding Unit TestingUnderstanding Unit Testing
Understanding Unit Testingikhwanhayat
 
Unit testing best practices
Unit testing best practicesUnit testing best practices
Unit testing best practicesnickokiss
 
TestNG Session presented in PB
TestNG Session presented in PBTestNG Session presented in PB
TestNG Session presented in PBAbhishek Yadav
 

What's hot (20)

TestNG Annotations in Selenium | Edureka
TestNG Annotations in Selenium | EdurekaTestNG Annotations in Selenium | Edureka
TestNG Annotations in Selenium | Edureka
 
JUnit 5
JUnit 5JUnit 5
JUnit 5
 
testng
testngtestng
testng
 
Junit
JunitJunit
Junit
 
Unit Testing And Mocking
Unit Testing And MockingUnit Testing And Mocking
Unit Testing And Mocking
 
TestNG Framework
TestNG Framework TestNG Framework
TestNG Framework
 
Mocking in Java with Mockito
Mocking in Java with MockitoMocking in Java with Mockito
Mocking in Java with Mockito
 
Unit Testing in Java
Unit Testing in JavaUnit Testing in Java
Unit Testing in Java
 
JUnit & Mockito, first steps
JUnit & Mockito, first stepsJUnit & Mockito, first steps
JUnit & Mockito, first steps
 
Unit testing framework
Unit testing frameworkUnit testing framework
Unit testing framework
 
An Introduction to Unit Testing
An Introduction to Unit TestingAn Introduction to Unit Testing
An Introduction to Unit Testing
 
Workshop unit test
Workshop   unit testWorkshop   unit test
Workshop unit test
 
Unit Testing in Angular
Unit Testing in AngularUnit Testing in Angular
Unit Testing in Angular
 
Testing with Spring: An Introduction
Testing with Spring: An IntroductionTesting with Spring: An Introduction
Testing with Spring: An Introduction
 
Understanding Unit Testing
Understanding Unit TestingUnderstanding Unit Testing
Understanding Unit Testing
 
Unit Testing (C#)
Unit Testing (C#)Unit Testing (C#)
Unit Testing (C#)
 
Unit Testing
Unit TestingUnit Testing
Unit Testing
 
Mockito
MockitoMockito
Mockito
 
Unit testing best practices
Unit testing best practicesUnit testing best practices
Unit testing best practices
 
TestNG Session presented in PB
TestNG Session presented in PBTestNG Session presented in PB
TestNG Session presented in PB
 

Similar to JUNit Presentation

Google mock training
Google mock trainingGoogle mock training
Google mock trainingThierry Gayet
 
A la découverte des google/mock (aka gmock)
A la découverte des google/mock (aka gmock)A la découverte des google/mock (aka gmock)
A la découverte des google/mock (aka gmock)Thierry Gayet
 
31b - JUnit and Mockito.pdf
31b - JUnit and Mockito.pdf31b - JUnit and Mockito.pdf
31b - JUnit and Mockito.pdfgauravavam
 
An Introduction To Unit Testing and TDD
An Introduction To Unit Testing and TDDAn Introduction To Unit Testing and TDD
An Introduction To Unit Testing and TDDAhmed Ehab AbdulAziz
 
Accord.Net: Looking for a Bug that Could Help Machines Conquer Humankind
Accord.Net: Looking for a Bug that Could Help Machines Conquer HumankindAccord.Net: Looking for a Bug that Could Help Machines Conquer Humankind
Accord.Net: Looking for a Bug that Could Help Machines Conquer HumankindPVS-Studio
 
2011 py con
2011 py con2011 py con
2011 py conEing Ong
 
Introduction To UnitTesting & JUnit
Introduction To UnitTesting & JUnitIntroduction To UnitTesting & JUnit
Introduction To UnitTesting & JUnitMindfire Solutions
 
Dependency Injection in .NET applications
Dependency Injection in .NET applicationsDependency Injection in .NET applications
Dependency Injection in .NET applicationsBabak Naffas
 
Testing Options in Java
Testing Options in JavaTesting Options in Java
Testing Options in JavaMichael Fons
 
Comparative Development Methodologies
Comparative Development MethodologiesComparative Development Methodologies
Comparative Development Methodologieselliando dias
 
Software Engineering - RS3
Software Engineering - RS3Software Engineering - RS3
Software Engineering - RS3AtakanAral
 
Working Effectively With Legacy Code
Working Effectively With Legacy CodeWorking Effectively With Legacy Code
Working Effectively With Legacy CodeNaresh Jain
 
Hyper-pragmatic Pure FP testing with distage-testkit
Hyper-pragmatic Pure FP testing with distage-testkitHyper-pragmatic Pure FP testing with distage-testkit
Hyper-pragmatic Pure FP testing with distage-testkit7mind
 
Unit Testing in Flutter - From Workflow Essentials to Complex Scenarios
Unit Testing in Flutter - From Workflow Essentials to Complex ScenariosUnit Testing in Flutter - From Workflow Essentials to Complex Scenarios
Unit Testing in Flutter - From Workflow Essentials to Complex ScenariosFlutter Agency
 
J unit presentation
J unit presentationJ unit presentation
J unit presentationPriya Sharma
 

Similar to JUNit Presentation (20)

Google mock training
Google mock trainingGoogle mock training
Google mock training
 
Why test with flex unit
Why test with flex unitWhy test with flex unit
Why test with flex unit
 
A la découverte des google/mock (aka gmock)
A la découverte des google/mock (aka gmock)A la découverte des google/mock (aka gmock)
A la découverte des google/mock (aka gmock)
 
31b - JUnit and Mockito.pdf
31b - JUnit and Mockito.pdf31b - JUnit and Mockito.pdf
31b - JUnit and Mockito.pdf
 
An Introduction To Unit Testing and TDD
An Introduction To Unit Testing and TDDAn Introduction To Unit Testing and TDD
An Introduction To Unit Testing and TDD
 
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven Development
 
Accord.Net: Looking for a Bug that Could Help Machines Conquer Humankind
Accord.Net: Looking for a Bug that Could Help Machines Conquer HumankindAccord.Net: Looking for a Bug that Could Help Machines Conquer Humankind
Accord.Net: Looking for a Bug that Could Help Machines Conquer Humankind
 
2011 py con
2011 py con2011 py con
2011 py con
 
Introduction To UnitTesting & JUnit
Introduction To UnitTesting & JUnitIntroduction To UnitTesting & JUnit
Introduction To UnitTesting & JUnit
 
J Unit
J UnitJ Unit
J Unit
 
Dependency Injection in .NET applications
Dependency Injection in .NET applicationsDependency Injection in .NET applications
Dependency Injection in .NET applications
 
Testing Options in Java
Testing Options in JavaTesting Options in Java
Testing Options in Java
 
Comparative Development Methodologies
Comparative Development MethodologiesComparative Development Methodologies
Comparative Development Methodologies
 
Unit Testing
Unit TestingUnit Testing
Unit Testing
 
Software Engineering - RS3
Software Engineering - RS3Software Engineering - RS3
Software Engineering - RS3
 
Working Effectively With Legacy Code
Working Effectively With Legacy CodeWorking Effectively With Legacy Code
Working Effectively With Legacy Code
 
Hyper-pragmatic Pure FP testing with distage-testkit
Hyper-pragmatic Pure FP testing with distage-testkitHyper-pragmatic Pure FP testing with distage-testkit
Hyper-pragmatic Pure FP testing with distage-testkit
 
Unit Testing in Flutter - From Workflow Essentials to Complex Scenarios
Unit Testing in Flutter - From Workflow Essentials to Complex ScenariosUnit Testing in Flutter - From Workflow Essentials to Complex Scenarios
Unit Testing in Flutter - From Workflow Essentials to Complex Scenarios
 
UI Testing
UI TestingUI Testing
UI Testing
 
J unit presentation
J unit presentationJ unit presentation
J unit presentation
 

Recently uploaded

KLINIK BATA Jual obat penggugur kandungan 087776558899 ABORSI JANIN KEHAMILAN...
KLINIK BATA Jual obat penggugur kandungan 087776558899 ABORSI JANIN KEHAMILAN...KLINIK BATA Jual obat penggugur kandungan 087776558899 ABORSI JANIN KEHAMILAN...
KLINIK BATA Jual obat penggugur kandungan 087776558899 ABORSI JANIN KEHAMILAN...Cara Menggugurkan Kandungan 087776558899
 
2k Shots ≽ 9205541914 ≼ Call Girls In Dashrath Puri (Delhi)
2k Shots ≽ 9205541914 ≼ Call Girls In Dashrath Puri (Delhi)2k Shots ≽ 9205541914 ≼ Call Girls In Dashrath Puri (Delhi)
2k Shots ≽ 9205541914 ≼ Call Girls In Dashrath Puri (Delhi)Delhi Call girls
 
LC_YouSaidYes_NewBelieverBookletDone.pdf
LC_YouSaidYes_NewBelieverBookletDone.pdfLC_YouSaidYes_NewBelieverBookletDone.pdf
LC_YouSaidYes_NewBelieverBookletDone.pdfpastor83
 
Pokemon Go... Unraveling the Conspiracy Theory
Pokemon Go... Unraveling the Conspiracy TheoryPokemon Go... Unraveling the Conspiracy Theory
Pokemon Go... Unraveling the Conspiracy Theorydrae5
 
2k Shots ≽ 9205541914 ≼ Call Girls In Palam (Delhi)
2k Shots ≽ 9205541914 ≼ Call Girls In Palam (Delhi)2k Shots ≽ 9205541914 ≼ Call Girls In Palam (Delhi)
2k Shots ≽ 9205541914 ≼ Call Girls In Palam (Delhi)Delhi Call girls
 
WOMEN EMPOWERMENT women empowerment.pptx
WOMEN EMPOWERMENT women empowerment.pptxWOMEN EMPOWERMENT women empowerment.pptx
WOMEN EMPOWERMENT women empowerment.pptxpadhand000
 
Top Rated Pune Call Girls Tingre Nagar ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated  Pune Call Girls Tingre Nagar ⟟ 6297143586 ⟟ Call Me For Genuine Se...Top Rated  Pune Call Girls Tingre Nagar ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated Pune Call Girls Tingre Nagar ⟟ 6297143586 ⟟ Call Me For Genuine Se...Call Girls in Nagpur High Profile
 
the Husband rolesBrown Aesthetic Cute Group Project Presentation
the Husband rolesBrown Aesthetic Cute Group Project Presentationthe Husband rolesBrown Aesthetic Cute Group Project Presentation
the Husband rolesBrown Aesthetic Cute Group Project Presentationbrynpueblos04
 
call Now 9811711561 Cash Payment乂 Call Girls in Dwarka Mor
call Now 9811711561 Cash Payment乂 Call Girls in Dwarka Morcall Now 9811711561 Cash Payment乂 Call Girls in Dwarka Mor
call Now 9811711561 Cash Payment乂 Call Girls in Dwarka Morvikas rana
 
$ Love Spells^ 💎 (310) 882-6330 in West Virginia, WV | Psychic Reading Best B...
$ Love Spells^ 💎 (310) 882-6330 in West Virginia, WV | Psychic Reading Best B...$ Love Spells^ 💎 (310) 882-6330 in West Virginia, WV | Psychic Reading Best B...
$ Love Spells^ 💎 (310) 882-6330 in West Virginia, WV | Psychic Reading Best B...PsychicRuben LoveSpells
 
2k Shots ≽ 9205541914 ≼ Call Girls In Mukherjee Nagar (Delhi)
2k Shots ≽ 9205541914 ≼ Call Girls In Mukherjee Nagar (Delhi)2k Shots ≽ 9205541914 ≼ Call Girls In Mukherjee Nagar (Delhi)
2k Shots ≽ 9205541914 ≼ Call Girls In Mukherjee Nagar (Delhi)Delhi Call girls
 
2k Shots ≽ 9205541914 ≼ Call Girls In Jasola (Delhi)
2k Shots ≽ 9205541914 ≼ Call Girls In Jasola (Delhi)2k Shots ≽ 9205541914 ≼ Call Girls In Jasola (Delhi)
2k Shots ≽ 9205541914 ≼ Call Girls In Jasola (Delhi)Delhi Call girls
 

Recently uploaded (14)

KLINIK BATA Jual obat penggugur kandungan 087776558899 ABORSI JANIN KEHAMILAN...
KLINIK BATA Jual obat penggugur kandungan 087776558899 ABORSI JANIN KEHAMILAN...KLINIK BATA Jual obat penggugur kandungan 087776558899 ABORSI JANIN KEHAMILAN...
KLINIK BATA Jual obat penggugur kandungan 087776558899 ABORSI JANIN KEHAMILAN...
 
(Aarini) Russian Call Girls Surat Call Now 8250077686 Surat Escorts 24x7
(Aarini) Russian Call Girls Surat Call Now 8250077686 Surat Escorts 24x7(Aarini) Russian Call Girls Surat Call Now 8250077686 Surat Escorts 24x7
(Aarini) Russian Call Girls Surat Call Now 8250077686 Surat Escorts 24x7
 
2k Shots ≽ 9205541914 ≼ Call Girls In Dashrath Puri (Delhi)
2k Shots ≽ 9205541914 ≼ Call Girls In Dashrath Puri (Delhi)2k Shots ≽ 9205541914 ≼ Call Girls In Dashrath Puri (Delhi)
2k Shots ≽ 9205541914 ≼ Call Girls In Dashrath Puri (Delhi)
 
LC_YouSaidYes_NewBelieverBookletDone.pdf
LC_YouSaidYes_NewBelieverBookletDone.pdfLC_YouSaidYes_NewBelieverBookletDone.pdf
LC_YouSaidYes_NewBelieverBookletDone.pdf
 
Pokemon Go... Unraveling the Conspiracy Theory
Pokemon Go... Unraveling the Conspiracy TheoryPokemon Go... Unraveling the Conspiracy Theory
Pokemon Go... Unraveling the Conspiracy Theory
 
2k Shots ≽ 9205541914 ≼ Call Girls In Palam (Delhi)
2k Shots ≽ 9205541914 ≼ Call Girls In Palam (Delhi)2k Shots ≽ 9205541914 ≼ Call Girls In Palam (Delhi)
2k Shots ≽ 9205541914 ≼ Call Girls In Palam (Delhi)
 
WOMEN EMPOWERMENT women empowerment.pptx
WOMEN EMPOWERMENT women empowerment.pptxWOMEN EMPOWERMENT women empowerment.pptx
WOMEN EMPOWERMENT women empowerment.pptx
 
Top Rated Pune Call Girls Tingre Nagar ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated  Pune Call Girls Tingre Nagar ⟟ 6297143586 ⟟ Call Me For Genuine Se...Top Rated  Pune Call Girls Tingre Nagar ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated Pune Call Girls Tingre Nagar ⟟ 6297143586 ⟟ Call Me For Genuine Se...
 
(Anamika) VIP Call Girls Navi Mumbai Call Now 8250077686 Navi Mumbai Escorts ...
(Anamika) VIP Call Girls Navi Mumbai Call Now 8250077686 Navi Mumbai Escorts ...(Anamika) VIP Call Girls Navi Mumbai Call Now 8250077686 Navi Mumbai Escorts ...
(Anamika) VIP Call Girls Navi Mumbai Call Now 8250077686 Navi Mumbai Escorts ...
 
the Husband rolesBrown Aesthetic Cute Group Project Presentation
the Husband rolesBrown Aesthetic Cute Group Project Presentationthe Husband rolesBrown Aesthetic Cute Group Project Presentation
the Husband rolesBrown Aesthetic Cute Group Project Presentation
 
call Now 9811711561 Cash Payment乂 Call Girls in Dwarka Mor
call Now 9811711561 Cash Payment乂 Call Girls in Dwarka Morcall Now 9811711561 Cash Payment乂 Call Girls in Dwarka Mor
call Now 9811711561 Cash Payment乂 Call Girls in Dwarka Mor
 
$ Love Spells^ 💎 (310) 882-6330 in West Virginia, WV | Psychic Reading Best B...
$ Love Spells^ 💎 (310) 882-6330 in West Virginia, WV | Psychic Reading Best B...$ Love Spells^ 💎 (310) 882-6330 in West Virginia, WV | Psychic Reading Best B...
$ Love Spells^ 💎 (310) 882-6330 in West Virginia, WV | Psychic Reading Best B...
 
2k Shots ≽ 9205541914 ≼ Call Girls In Mukherjee Nagar (Delhi)
2k Shots ≽ 9205541914 ≼ Call Girls In Mukherjee Nagar (Delhi)2k Shots ≽ 9205541914 ≼ Call Girls In Mukherjee Nagar (Delhi)
2k Shots ≽ 9205541914 ≼ Call Girls In Mukherjee Nagar (Delhi)
 
2k Shots ≽ 9205541914 ≼ Call Girls In Jasola (Delhi)
2k Shots ≽ 9205541914 ≼ Call Girls In Jasola (Delhi)2k Shots ≽ 9205541914 ≼ Call Girls In Jasola (Delhi)
2k Shots ≽ 9205541914 ≼ Call Girls In Jasola (Delhi)
 

JUNit Presentation

  • 1. An Introduction to JUnit Animesh Kumar
  • 2. Toyota 2 Impetus Confidential http://blog.crisp.se/henrikkniberg/2010/03/16/1268757660000.html Toyota’s Prius example A 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 expensive Reality 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? 3 Impetus Confidential
  • 4. Test Driven Development An 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_development 4 Impetus Confidential
  • 5. What is Unit Testing? A Unit Test is a procedure to validate a single Functionality of an application. One Functionality  One Unit Test Unit 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. 5 Impetus 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. 6 Impetus Confidential
  • 7. JUnit – An introduction JUnit 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. 7 Impetus 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.  8 Impetus Confidential
  • 9.
  • 10.
  • 11. Write a test case Define a subclass of junit.framework.TestCase public 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 } 11 Impetus Confidential
  • 12. Write a test case Override setUp() method to perform initialization. @Override protected void setUp () { // Initialize anything, like calc = new Calculator(); } Override tearDown() method to clean up. @Override protected void tearDown () { // Clean up, like calc = null; } 12 Impetus Confidential
  • 13. Asserting expectations assertEquals (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) 13 Impetus Confidential
  • 14. Failure? JUnit uses the term failure for a test that fails expectedly.That is An assertion was not valid or A fail() was encountered. 14 Impetus Confidential
  • 15. Write a test case public 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. 15 Impetus Confidential
  • 16. Write a test suite Write 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; } } 16 Impetus Confidential
  • 17. Run your tests You 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. 17 Impetus Confidential
  • 18. Run your tests JUnit 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.TestRunnerAllTests or, junit.textui.TestRunner.run(AllTests.class); Graphical Runner >> java junit.swingui.TestRunnerAllTests or, junit.swingui.TestRunner.run(AllTests.class); IDE like Eclipse, NetBeans “Run as JUnit” 18 Impetus Confidential
  • 19.
  • 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. Mocks Mocking 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. 20 Impetus Confidential
  • 23. EasyMock EasyMock is an open-source java library to help you create Mock Objects. Flow: Expect => Replay => Verify userService = EasyMock.createMock(IUserService.class); 1 User user = ... // EasyMock .expect (userService.isRegisteredUser(user)) 2 .andReturn (true); 3 EasyMock.replay(userService); 4 assertTrue(userService.isRegisteredUser(user)); 5 Modes: Strict and Nice 21 Impetus Confidential
  • 24. JUnit and Eclipse 22 Impetus Confidential
  • 25. JUnit and build tools 23 Impetus Confidential Apache Maven > mvn test > mvn -Dtest=MyTestCase,MyOtherTestCase test Apache 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? 24 Impetus Confidential Designed to call methods. This works great for methods that just return results Methods that change the state of the object could turn out to be tricky to test Difficult to unit test GUI code Encourages “functional” style of coding This can be a good thing
  • 27. How to approach? 25 Impetus Confidential Test 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. Resources 26 Impetus Confidential Book: Manning: JUnit in Action http://www.junit.org/index.htm http://www.cs.umanitoba.ca/~eclipse/10-JUnit.pdf http://supportweb.cs.bham.ac.uk/documentation/tutorials/docsystem/build/tutorials/junit/junit.pdf http://junit.sourceforge.net/javadoc/junit/framework/

Editor's Notes

  1. Long hourswith stoned debuggers!
  2. Long hourswith stoned debuggers!
  3. Long hourswith stoned debuggers!
  4. Example of calculator!
  5. Example of calculator!
  6. Long hourswith stoned debuggers!
  7. Long hourswith stoned debuggers!
  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!