An Introduction to JUnit<br />Animesh Kumar<br />
Toyota<br />2<br />Impetus Confidential<br />http://blog.crisp.se/henrikkniberg/2010/03/16/1268757660000.html<br />Toyota’...
Why write tests?<br />Write a lot of code, and one day something will stopworking!<br />Fixing a bug is easy, but how abou...
Test Driven Development<br />An evolutionary approach to development where first you write a Test and then add Functionali...
What is Unit Testing?<br />A Unit Test is a procedure to validate a single Functionality of an application. <br />One Func...
What do we get?<br />Obviously, we get tests to validate the functionalities, but that’s not all…<br />One part of the pro...
JUnit – An introduction<br />JUnit is a unit testing framework for the java programming language. <br />It comes from the ...
Why choose JUnit?<br />Of course there are many tools like JUnit, but none like it. <br />JUnit is simple and elegant. <br...
Design of JUnit<br />9<br />Impetus Confidential<br /><ul><li>junit.framework.TestCase is the abstract command class which...
junit.framework.TestSuite is a composite of other tests, either TestCaseor TestSuite. This behavior helps you create hiera...
Write a test case<br />Define a subclass of junit.framework.TestCase<br />public class CalculatorTest extends TestCase {<b...
Write a test case<br />Override setUp() method to perform initialization.<br />@Override<br />protected void setUp () {<br...
Asserting expectations<br />assertEquals (expected, actual) <br />assertEquals (message, expected, actual) <br />assertEqu...
Failure?<br />JUnit uses the term failure for a test that fails expectedly.That is<br />An assertion was not valid  or <br...
Write a test case<br />public class CalculatorTest extends TestCase {<br />	// initialize<br />	protected void setUp ()......
Write a test suite<br />Write a class with a static method suite() that creates a junit.framework.TestSuitecontaining all ...
Run your tests<br />You can either run TestCase or TestSuite instances.<br />A TestSuite will automatically run all its re...
Run your tests<br />JUnit comes with TestRunners that run your tests and immediately provide you with feedbacks, errors, a...
Test maintenance<br />19<br />Impetus Confidential<br /><ul><li>Create 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 hi...
Mocks<br />Mocking is a way to deal with third-party dependencies inside TestCase. <br />Mocks create FAKE objects to mock...
EasyMock<br />EasyMock is an open-source java library to help you create Mock Objects.<br />Flow:  Expect => Replay => Ver...
JUnit and Eclipse<br />22<br />Impetus Confidential<br />
JUnit and build tools<br />23<br />Impetus Confidential<br />Apache Maven<br />> mvn test<br />> mvn -Dtest=MyTestCase,MyO...
Side effects – good or bad?<br />24<br />Impetus Confidential<br />Designed to call methods.<br />This works great for met...
How to approach?<br />25<br />Impetus Confidential<br />Test a little, Code a little, Test a little, Code a little … doesn...
Upcoming SlideShare
Loading in...5
×

JUNit Presentation

4,997

Published on

Published in: Self Improvement
0 Comments
3 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total Views
4,997
On Slideshare
0
From Embeds
0
Number of Embeds
3
Actions
Shares
0
Downloads
268
Comments
0
Likes
3
Embeds 0
No embeds

No notes for slide
  • Long hourswith stoned debuggers!
  • Long hourswith stoned debuggers!
  • Long hourswith stoned debuggers!
  • Example of calculator!
  • Example of calculator!
  • Long hourswith stoned debuggers!
  • Long hourswith stoned debuggers!
  • Long hourswith stoned debuggers!
  • Long hourswith stoned debuggers!
  • Long hourswith stoned debuggers!
  • Long hourswith stoned debuggers!
  • Long hourswith stoned debuggers!
  • Long hourswith stoned debuggers!
  • Long hourswith stoned debuggers!
  • Long hourswith stoned debuggers!
  • Long hourswith stoned debuggers!
  • Long hourswith stoned debuggers!
  • Long hourswith stoned debuggers!
  • Long hourswith stoned debuggers!
  • Long hourswith stoned debuggers!
  • Long hourswith stoned debuggers!
  • Long hourswith stoned debuggers!
  • Long hourswith stoned debuggers!
  • Long hourswith stoned debuggers!
  • Long hourswith stoned debuggers!
  • JUNit Presentation

    1. 1. An Introduction to JUnit<br />Animesh Kumar<br />
    2. 2. Toyota<br />2<br />Impetus Confidential<br />http://blog.crisp.se/henrikkniberg/2010/03/16/1268757660000.html<br />Toyota’s Prius example<br />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<br />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".<br />
    3. 3. Why write tests?<br />Write a lot of code, and one day something will stopworking!<br />Fixing a bug is easy, but how about pinning it down? <br />You never know where the ripples of your fixes can go.<br />Are you sure the demon is dead? <br />3<br />Impetus Confidential<br />
    4. 4. Test Driven Development<br />An evolutionary approach to development where first you write a Test and then add Functionality to pass the test. <br />Image courtesy: http://en.wikipedia.org/wiki/Test-driven_development<br />4<br />Impetus Confidential<br />
    5. 5. What is Unit Testing?<br />A Unit Test is a procedure to validate a single Functionality of an application. <br />One Functionality  One Unit Test<br />Unit Tests are automated and self-checked. <br />They run in isolation of each other.<br />They do NOT depend on or connect to external resources, like DB, Network etc.<br />They can run in any order and even parallel to each other and that will be fine. <br />5<br />Impetus Confidential<br />
    6. 6. What do we get?<br />Obviously, we get tests to validate the functionalities, but that’s not all…<br />One part of the program is isolated from others, i.e. proper separation of concerns. <br />An ecology to foster Interface/Contract approached programming. <br />Interfaces are documented. <br />Refactoring made smooth like butter lathered floor. <br />Quick bug identification.<br />6<br />Impetus Confidential<br />
    7. 7. JUnit – An introduction<br />JUnit is a unit testing framework for the java programming language. <br />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. <br /> Kent Beck and Erich Gamma originally wrote this framework for ‘smalltalk’, and it was called SUnit. Later it rippled into other languages. <br />7<br />Impetus Confidential<br />
    8. 8. Why choose JUnit?<br />Of course there are many tools like JUnit, but none like it. <br />JUnit is simple and elegant. <br />JUnit checks its own results and provide immediate customized feedback. <br />JUnit is hierarchal. <br />JUnit has the widest IDE support, Eclipse, NetBeans, IntelliJ IDEA … you name it.<br />JUnit is recognized by popular build tools like, ant, maven etc.<br />And… it’s free.  <br />8<br />Impetus Confidential<br />
    9. 9. Design of JUnit<br />9<br />Impetus Confidential<br /><ul><li>junit.framework.TestCase is the abstract command class which you subclass into your Test Classes.
    10. 10. junit.framework.TestSuite is a composite of other tests, either TestCaseor TestSuite. This behavior helps you create hierarchal tests with depth control. </li></li></ul><li>Design of JUnit<br />10<br />Impetus Confidential<br />Image Courtesy: JUnit: A Cook’s Tour<br />
    11. 11. Write a test case<br />Define a subclass of junit.framework.TestCase<br />public class CalculatorTest extends TestCase {<br />}<br />Define one or more testXXX() methods that can perform the tests and assert expected results. <br />public void testAddition () {<br /> Calculator calc = new Calculator();<br />int expected = 25;<br />int result = calc.add (10, 15);<br />assertEquals (result, expected); // asserting<br />}<br />11<br />Impetus Confidential<br />
    12. 12. Write a test case<br />Override setUp() method to perform initialization.<br />@Override<br />protected void setUp () {<br /> // Initialize anything, like<br /> calc = new Calculator();<br />}<br />Override tearDown() method to clean up.<br />@Override<br />protected void tearDown () {<br /> // Clean up, like<br /> calc = null;<br />}<br />12<br />Impetus Confidential<br />
    13. 13. Asserting expectations<br />assertEquals (expected, actual) <br />assertEquals (message, expected, actual) <br />assertEquals (expected, actual, delta)<br />assertEquals (message, expected, actual, delta) <br />assertFalse ((message)condition) <br />Assert(Not)Null (object) <br />Assert(Not)Null (message, object) <br />Assert(Not)Same (expected, actual) <br />Assert(Not)Same (message, expected, actual) <br />assertTrue ((message), condition)<br />13<br />Impetus Confidential<br />
    14. 14. Failure?<br />JUnit uses the term failure for a test that fails expectedly.That is<br />An assertion was not valid or <br />A fail() was encountered. <br />14<br />Impetus Confidential<br />
    15. 15. Write a test case<br />public class CalculatorTest extends TestCase {<br /> // initialize<br /> protected void setUp ()... Spublic void testAddition ()... T1<br /> public void testSubtraction ()... T2<br /> public void testMultiplication ()... T3<br /> // clean up<br /> protected void tearDownUp ()... C <br />}<br />Execution will be S T1 C, S T2 C, S T3 Cin any order. <br />15<br />Impetus Confidential<br />
    16. 16. Write a test suite<br />Write a class with a static method suite() that creates a junit.framework.TestSuitecontaining all the Tests. <br />public class AllTests {<br /> public static Test suite() {<br />TestSuite suite = new TestSuite();<br />suite.addTestSuite(<test-1>.class);<br />suite.addTestSuite(<test-2>.class);<br /> return suite;<br /> }<br />}<br />16<br />Impetus Confidential<br />
    17. 17. Run your tests<br />You can either run TestCase or TestSuite instances.<br />A TestSuite will automatically run all its registered TestCase instances. <br />All public testXXX() methods of a TestCase will be executed. But there is no guarantee of the order. <br />17<br />Impetus Confidential<br />
    18. 18. Run your tests<br />JUnit comes with TestRunners that run your tests and immediately provide you with feedbacks, errors, and status of completion. <br />JUnit has Textual and Graphical test runners. <br />Textual Runner <br />>> java junit.textui.TestRunnerAllTests<br />or,<br />junit.textui.TestRunner.run(AllTests.class);<br />Graphical Runner <br />>> java junit.swingui.TestRunnerAllTests<br />or,<br />junit.swingui.TestRunner.run(AllTests.class);<br />IDE like Eclipse, NetBeans “Run as JUnit”<br />18<br />Impetus Confidential<br />
    19. 19. Test maintenance<br />19<br />Impetus Confidential<br /><ul><li>Create 2 separate directories for source and testcodes.
    20. 20. Mirror source package structure into test.
    21. 21. Define a TestSuite for each java package that would contain all TestCase instances for this package. This will create a hierarchy of Tests. </li></ul>> com -<br />> impetus - AllTests<br />> Book - BookTests<br />. AddBook - AddBookTest<br />. DeleteBook - DeleteBookTest<br />. ListBooks - ListBooksTest<br />> Library - LibraryTests<br />> User - UserTests<br />
    22. 22. Mocks<br />Mocking is a way to deal with third-party dependencies inside TestCase. <br />Mocks create FAKE objects to mock a contract behavior. <br />Mocks help make tests more unitary. <br />20<br />Impetus Confidential<br />
    23. 23. EasyMock<br />EasyMock is an open-source java library to help you create Mock Objects.<br />Flow: Expect => Replay => Verify<br />userService = EasyMock.createMock(IUserService.class); 1<br />User user = ... //<br />EasyMock<br /> .expect (userService.isRegisteredUser(user)) 2<br /> .andReturn (true); 3<br />EasyMock.replay(userService); 4<br />assertTrue(userService.isRegisteredUser(user)); 5<br />Modes: Strict and Nice<br />21<br />Impetus Confidential<br />
    24. 24. JUnit and Eclipse<br />22<br />Impetus Confidential<br />
    25. 25. JUnit and build tools<br />23<br />Impetus Confidential<br />Apache Maven<br />> mvn test<br />> mvn -Dtest=MyTestCase,MyOtherTestCase test<br />Apache Ant<br /><junitprintsummary="yes" haltonfailure="yes"><br /> <test name="my.test.TestCase"/><br /></junit><br /><junitprintsummary="yes" haltonfailure="yes"><br /> <batchtest fork="yes" todir="${reports.tests}"><br /> <fileset dir="${src.tests}"><br /> <include name="**/*Test*.java"/><br /> <exclude name="**/AllTests.java"/><br /> </fileset><br /> </batchtest><br /></junit><br />
    26. 26. Side effects – good or bad?<br />24<br />Impetus Confidential<br />Designed to call methods.<br />This works great for methods that just return results<br />Methods that change the state of the object could turn out to be tricky to test<br />Difficult to unit test GUI code<br />Encourages “functional” style of coding<br />This can be a good thing<br />
    27. 27. How to approach?<br />25<br />Impetus Confidential<br />Test a little, Code a little, Test a little, Code a little … doesn’t it rhyme? ;) <br />Write tests to validate functionality, not functions. <br />If tempted to write System.out.println() to debug something, better write a test for it. <br />If a bug is found, write a test to expose the bug. <br />
    28. 28. Resources<br />26<br />Impetus Confidential<br />Book: Manning: JUnit in Action<br />http://www.junit.org/index.htm<br />http://www.cs.umanitoba.ca/~eclipse/10-JUnit.pdf<br />http://supportweb.cs.bham.ac.uk/documentation/tutorials/docsystem/build/tutorials/junit/junit.pdf<br />http://junit.sourceforge.net/javadoc/junit/framework/<br />
    1. A particular slide catching your eye?

      Clipping is a handy way to collect important slides you want to go back to later.

    ×