J-Unit 4.x Writing Test Cases
Why J-Unit ? For Test Driven Development. Write the test first….. Then code to make your test pass Official Definition: JUnit  is a  unit testing   framework  for the  Java programming language . JUnit has been important in the development of  test-driven development , and is one of a family of unit testing frameworks collectively known as  xUnit  that originated with  SUnit .
What is J-Unit ? JUnit features include:  Assertions for testing expected results  Test fixtures for sharing common test data  Test runners for running tests
@Test @Test    public   void  addition() {          assertEquals(12, simpleMath.add(7, 5));     }         Mark your test cases with @Test annotations. You don’t need to prefix your test cases with “test”.  In addition, your class does not need to extend from “TestCase” class
@Before   @Before     public   void  preTestRun() {          simpleMath =  new  SimpleMath();     }         Use @Before and @After annotations for “setup” and “tearDown” methods respectively. They run before and after every test case
@After @After    public   void  postTestRun() {          simpleMath =  null ;     }   
@ BeforeClass and @AfterClass @BeforeClass    public   static   void  runBeforeClass() {          // run for one time before all test cases      }         @AfterClass    public   static   void  runAfterClass() {          // run for one time after all test cases      }    Use @BeforeClass and @AfterClass annotations for class wide “setup” and “tearDown” respectively. Think them as one time setup and tearDown. They run for one time before and after all test cases.
Exception Handling @Test(expected = ArithmeticException. class )     public   void  divisionWithException() {          // divide by zero           simpleMath.divide(1, 0);     }    Use “expected” paramater with @Test annotation for test cases that expect exception. Write the class name of the exception that will be thrown.
@Ignore @Ignore("Not Ready to Run")     @Test    public   void  multiplication() {          assertEquals(15, simpleMath.multiply(3, 5));     }    Put @Ignore annotation for test cases you want to ignore.   You can add a string parameter that defines the reason of ignorance if you want.
Assertions
Timeout @Test(timeout = 1000)     public   void  infinity() {          while  ( true )              ;     }    Define a timeout period in milliseconds with “timeout” parameter. The test fails when the timeout period exceeds.
Ant    Html Reports Ensure that Ant's optional. jar file is either in your CLASSPATH or exists in your $ANT_HOME/lib directory. Add an ANT property for the directory containing the HTML reports: <property name=&quot;test.reports&quot; value=&quot;./reports&quot; />  Define the Ant task for running JUnit and generating reports:
Ant    Html Reports Contd…. <target name=&quot;test-html&quot;>  <junit fork=&quot;yes&quot; printsummary=&quot;no“ haltonfailure=&quot;no&quot;>  <batchtest fork=&quot;yes&quot; todir=&quot;${test.reports}&quot; >  <fileset dir=&quot;${classes}&quot;>  <include name=&quot;**/*Test.class&quot; />  </fileset>  </batchtest>  <formatter type=&quot;xml&quot; />  <classpath refid=&quot;test.classpath&quot; /> </junit> <junitreport todir=&quot;${test.reports}&quot;>  <fileset dir=&quot;${test.reports}&quot;>  <include name=&quot;TEST-*.xml&quot; />  </fileset>  <report todir=&quot;${test.reports}&quot; />  </junitreport>  </target>
Ant    Html Reports Contd…. Run the test:  ant test-html
The Concept of Mocking  Test your code not third party dependencies Create an Object that will replace a real object
Use EasyMock Download easyMock.jar and put it in your classpath For mocking classes use EasyMock Extension
EasyMock….. Create a Mock Object EasyMock.createMock(InterfaceName.class) Set the Mock Object in the Class whose method you are testing EasyMock. expect (your mock object.method which you are mocking) Replay and Verify
Example…. package  com.sample.test; import   static  org.junit.Assert. assertEquals ; import  org.easymock.EasyMock; import  org.junit.After; import  org.junit.Before; import  org.junit.Test; public   class  SampleTest { SampleClassInterface sampleClassMock; Addition addition;
Example Contd…… @Test public   void  testLoad(){ EasyMock. expect (sampleClassMock.addition(10, 20)).andReturn( new  Integer(12)); EasyMock. replay (sampleClassMock); int  result = addition.add(10, 20); EasyMock. verify (sampleClassMock); assertEquals ( new  Integer(result),  new  Integer(12)); }
Example Contd….. @Before public   void  setup(){ addition =  new  Addition();  sampleClassMock = EasyMock. createMock (SampleClassInterface. class ); addition.setSampleClassInterface(sampleClassMock); System. out .println(&quot;Setup Method&quot;); }
Example Contd…. @After public   void  tearDown(){ System. out .println(&quot;Tear Down Method&quot;); }
Example Contd….. package  com.sample.test; public   class  Addition { private  SampleClassInterface sampleClass; //junit  public  Addition(SampleClass sampleClassInterface) { super (); this .sampleClass = sampleClassInterface; }
Example Contd….. public  Addition() { super (); } public   int   add( int  a,  int  b ){ int  result = sampleClass.addition(a,b); return  result; } public   void  setSampleClassInterface(SampleClassInterface sampleClassInterface) { this .sampleClass = sampleClassInterface; } }
Why Coverage….?? Code coverage  is a measure used in  software testing . It describes the degree to which the  source code  of a  program  has been tested. It is a form of testing that inspects the code directly and is therefore a form of  white box testing .
Why Coverage…..?? Contd… Think about how you can focus around the developer and how Code Coverage can be used with Unit Testing.  If you ask most developers if they do a good job testing their code, they would tell you yes. However in another study (Boris Beizer in Johnson 1994), the average programmer thought they tested around 95 percent of the code they wrote, but on further inspection the amount of actual code was more like 30 percent.
Why Coverage Contd….. Developers are under more and more stress to deliver more code in less time. Automated code Generation tools used…. Big Question  ??????? Do You Know Your Code……???
Why Coverage Contd…. This information can be very enlightening. Think about it... you exercise your application with Code Coverage turned on and the results come back as 35 percent coverage. What's the deal? Did you just run your application with the &quot;happy path&quot; only or did you truly exercise the application? If you did exercise the application, then it appears a great deal of code may not be needed.
Why Code Coverage…?? Another thing to keep in mind is the concept of condition’s in code.  For each condition another test has to be written to properly test the other side of the condition. Again, if the testing is only focused on one path, then it is most likely &quot;happy path&quot; testing.
Managers Boon… Once you get the use of Code Coverage down, it can be used for trending.  This is very useful for program managers and companies as a whole.
Managers Boon Contd….. For example, say that starting on week one we had 40 percent total coverage with unit test, week two we had 50 percent of coverage with unit tests, and week three we had 30 percent coverage with unit tests… what gives?  Well from week three to four it may have been that the amount of code stayed about the same and more unit tests were created, and between weeks four and five a lot of code was added and very few unit tests were added.
Code Coverage Tool EclEmma is a free Java code coverage tool for Eclipse, available under the Eclipse Public License. Internally it is based on the great EMMA Java code coverage tool, trying to adopt EMMA's philosophy for the Eclipse workbench: Fast develop/test cycle:  Launches from within the workbench like JUnit test runs can directly be analyzed for code coverage.
Code Coverage Tool Contd…… Rich coverage analysis:  Coverage results are immediately summarized and highlighted in the Java  source code  editors.  Non-invasive:  EclEmma does not require modifying your projects or performing any other setup.
Code Coverage Tool Contd…… Update Site for Eclipse 3.3 and Before Download the eclemma plugin….. Copy from features and plugins to the features and plugins of your eclipse…… Restart your eclipse through command line using eclipse –clean
Code Coverage Example….
Code Coverage
Generating Coverage Report……
Questions? Questions?
Thanks Happy Coding and Unit Testing.

More Related Content

PPTX
Introduction To J unit
PPS
Why Unit Testingl
PPTX
Java Unit Testing
PPS
JUnit Presentation
PPSX
PPT
JUnit 4
PPT
05 junit
PPTX
Unit Testing with JUnit4 by Ravikiran Janardhana
Introduction To J unit
Why Unit Testingl
Java Unit Testing
JUnit Presentation
JUnit 4
05 junit
Unit Testing with JUnit4 by Ravikiran Janardhana

What's hot (20)

PPT
PPTX
JUNit Presentation
PPTX
PDF
Unit testing with JUnit
PPTX
Testing with Junit4
PDF
PPTX
JUnit- A Unit Testing Framework
PPT
Simple Unit Testing With Netbeans 6.1
PPT
PPTX
JUnit 5 - The Next Generation of JUnit - Ted's Tool Time
PPTX
Unit Testing in Java
PDF
Test driven development - JUnit basics and best practices
PDF
Unit testing with JUnit
PDF
Unit testing with Junit
ODP
Testing In Java
PDF
Junit tutorial
PDF
What is JUnit? | Edureka
PPT
3 j unit
PPT
Automated Unit Testing
JUNit Presentation
Unit testing with JUnit
Testing with Junit4
JUnit- A Unit Testing Framework
Simple Unit Testing With Netbeans 6.1
JUnit 5 - The Next Generation of JUnit - Ted's Tool Time
Unit Testing in Java
Test driven development - JUnit basics and best practices
Unit testing with JUnit
Unit testing with Junit
Testing In Java
Junit tutorial
What is JUnit? | Edureka
3 j unit
Automated Unit Testing
Ad

Similar to J Unit (20)

ODP
Bring the fun back to java
PPTX
Code igniter unittest-part1
PPS
J unit presentation
PDF
Unit testing - A&BP CC
PPT
Mockito with a hint of PowerMock
DOCX
Test Driven Development
PPTX
Unit testing
PDF
Core Java Programming Language (JSE) : Chapter VIII - Exceptions and Assertions
PPTX
DotNet unit testing training
PPT
Google mock training
PDF
Unit Testing in Flutter - From Workflow Essentials to Complex Scenarios
PDF
Appium Automation with Kotlin
PPT
Working Effectively With Legacy Code
ODP
Presentation Unit Testing process
PPT
Junit and testNG
PPT
Testing And Drupal
PPTX
8-testing.pptx
PPT
Unit testing
PPT
Unit testing php-unit - phing - selenium_v2
PPTX
Junit4&testng presentation
Bring the fun back to java
Code igniter unittest-part1
J unit presentation
Unit testing - A&BP CC
Mockito with a hint of PowerMock
Test Driven Development
Unit testing
Core Java Programming Language (JSE) : Chapter VIII - Exceptions and Assertions
DotNet unit testing training
Google mock training
Unit Testing in Flutter - From Workflow Essentials to Complex Scenarios
Appium Automation with Kotlin
Working Effectively With Legacy Code
Presentation Unit Testing process
Junit and testNG
Testing And Drupal
8-testing.pptx
Unit testing
Unit testing php-unit - phing - selenium_v2
Junit4&testng presentation
Ad

Recently uploaded (20)

PDF
Advancing precision in air quality forecasting through machine learning integ...
PPTX
Internet of Everything -Basic concepts details
PPTX
Build Your First AI Agent with UiPath.pptx
PDF
The influence of sentiment analysis in enhancing early warning system model f...
PDF
Enhancing plagiarism detection using data pre-processing and machine learning...
PDF
INTERSPEECH 2025 「Recent Advances and Future Directions in Voice Conversion」
PDF
sbt 2.0: go big (Scala Days 2025 edition)
PDF
Auditboard EB SOX Playbook 2023 edition.
PPTX
MuleSoft-Compete-Deck for midddleware integrations
PDF
Produktkatalog für HOBO Datenlogger, Wetterstationen, Sensoren, Software und ...
PPTX
AI IN MARKETING- PRESENTED BY ANWAR KABIR 1st June 2025.pptx
PDF
Lung cancer patients survival prediction using outlier detection and optimize...
PPTX
future_of_ai_comprehensive_20250822032121.pptx
PDF
Transform-Your-Supply-Chain-with-AI-Driven-Quality-Engineering.pdf
PPT
Galois Field Theory of Risk: A Perspective, Protocol, and Mathematical Backgr...
PDF
sustainability-14-14877-v2.pddhzftheheeeee
PDF
Comparative analysis of machine learning models for fake news detection in so...
DOCX
Basics of Cloud Computing - Cloud Ecosystem
PDF
Convolutional neural network based encoder-decoder for efficient real-time ob...
PDF
The-Future-of-Automotive-Quality-is-Here-AI-Driven-Engineering.pdf
Advancing precision in air quality forecasting through machine learning integ...
Internet of Everything -Basic concepts details
Build Your First AI Agent with UiPath.pptx
The influence of sentiment analysis in enhancing early warning system model f...
Enhancing plagiarism detection using data pre-processing and machine learning...
INTERSPEECH 2025 「Recent Advances and Future Directions in Voice Conversion」
sbt 2.0: go big (Scala Days 2025 edition)
Auditboard EB SOX Playbook 2023 edition.
MuleSoft-Compete-Deck for midddleware integrations
Produktkatalog für HOBO Datenlogger, Wetterstationen, Sensoren, Software und ...
AI IN MARKETING- PRESENTED BY ANWAR KABIR 1st June 2025.pptx
Lung cancer patients survival prediction using outlier detection and optimize...
future_of_ai_comprehensive_20250822032121.pptx
Transform-Your-Supply-Chain-with-AI-Driven-Quality-Engineering.pdf
Galois Field Theory of Risk: A Perspective, Protocol, and Mathematical Backgr...
sustainability-14-14877-v2.pddhzftheheeeee
Comparative analysis of machine learning models for fake news detection in so...
Basics of Cloud Computing - Cloud Ecosystem
Convolutional neural network based encoder-decoder for efficient real-time ob...
The-Future-of-Automotive-Quality-is-Here-AI-Driven-Engineering.pdf

J Unit

  • 1. J-Unit 4.x Writing Test Cases
  • 2. Why J-Unit ? For Test Driven Development. Write the test first….. Then code to make your test pass Official Definition: JUnit is a unit testing framework for the Java programming language . JUnit has been important in the development of test-driven development , and is one of a family of unit testing frameworks collectively known as xUnit that originated with SUnit .
  • 3. What is J-Unit ? JUnit features include: Assertions for testing expected results Test fixtures for sharing common test data Test runners for running tests
  • 4. @Test @Test   public   void  addition() {         assertEquals(12, simpleMath.add(7, 5));    }       Mark your test cases with @Test annotations. You don’t need to prefix your test cases with “test”.  In addition, your class does not need to extend from “TestCase” class
  • 5. @Before  @Before   public   void  preTestRun() {         simpleMath =  new  SimpleMath();    }       Use @Before and @After annotations for “setup” and “tearDown” methods respectively. They run before and after every test case
  • 6. @After @After   public   void  postTestRun() {         simpleMath =  null ;    }   
  • 7. @ BeforeClass and @AfterClass @BeforeClass   public   static   void  runBeforeClass() {         // run for one time before all test cases    }       @AfterClass   public   static   void  runAfterClass() {         // run for one time after all test cases    }    Use @BeforeClass and @AfterClass annotations for class wide “setup” and “tearDown” respectively. Think them as one time setup and tearDown. They run for one time before and after all test cases.
  • 8. Exception Handling @Test(expected = ArithmeticException. class )    public   void  divisionWithException() {         // divide by zero         simpleMath.divide(1, 0);    }    Use “expected” paramater with @Test annotation for test cases that expect exception. Write the class name of the exception that will be thrown.
  • 9. @Ignore @Ignore(&quot;Not Ready to Run&quot;)    @Test   public   void  multiplication() {         assertEquals(15, simpleMath.multiply(3, 5));    }    Put @Ignore annotation for test cases you want to ignore. You can add a string parameter that defines the reason of ignorance if you want.
  • 11. Timeout @Test(timeout = 1000)    public   void  infinity() {         while  ( true )             ;    }    Define a timeout period in milliseconds with “timeout” parameter. The test fails when the timeout period exceeds.
  • 12. Ant  Html Reports Ensure that Ant's optional. jar file is either in your CLASSPATH or exists in your $ANT_HOME/lib directory. Add an ANT property for the directory containing the HTML reports: <property name=&quot;test.reports&quot; value=&quot;./reports&quot; /> Define the Ant task for running JUnit and generating reports:
  • 13. Ant  Html Reports Contd…. <target name=&quot;test-html&quot;> <junit fork=&quot;yes&quot; printsummary=&quot;no“ haltonfailure=&quot;no&quot;> <batchtest fork=&quot;yes&quot; todir=&quot;${test.reports}&quot; > <fileset dir=&quot;${classes}&quot;> <include name=&quot;**/*Test.class&quot; /> </fileset> </batchtest> <formatter type=&quot;xml&quot; /> <classpath refid=&quot;test.classpath&quot; /> </junit> <junitreport todir=&quot;${test.reports}&quot;> <fileset dir=&quot;${test.reports}&quot;> <include name=&quot;TEST-*.xml&quot; /> </fileset> <report todir=&quot;${test.reports}&quot; /> </junitreport> </target>
  • 14. Ant  Html Reports Contd…. Run the test: ant test-html
  • 15. The Concept of Mocking Test your code not third party dependencies Create an Object that will replace a real object
  • 16. Use EasyMock Download easyMock.jar and put it in your classpath For mocking classes use EasyMock Extension
  • 17. EasyMock….. Create a Mock Object EasyMock.createMock(InterfaceName.class) Set the Mock Object in the Class whose method you are testing EasyMock. expect (your mock object.method which you are mocking) Replay and Verify
  • 18. Example…. package com.sample.test; import static org.junit.Assert. assertEquals ; import org.easymock.EasyMock; import org.junit.After; import org.junit.Before; import org.junit.Test; public class SampleTest { SampleClassInterface sampleClassMock; Addition addition;
  • 19. Example Contd…… @Test public void testLoad(){ EasyMock. expect (sampleClassMock.addition(10, 20)).andReturn( new Integer(12)); EasyMock. replay (sampleClassMock); int result = addition.add(10, 20); EasyMock. verify (sampleClassMock); assertEquals ( new Integer(result), new Integer(12)); }
  • 20. Example Contd….. @Before public void setup(){ addition = new Addition(); sampleClassMock = EasyMock. createMock (SampleClassInterface. class ); addition.setSampleClassInterface(sampleClassMock); System. out .println(&quot;Setup Method&quot;); }
  • 21. Example Contd…. @After public void tearDown(){ System. out .println(&quot;Tear Down Method&quot;); }
  • 22. Example Contd….. package com.sample.test; public class Addition { private SampleClassInterface sampleClass; //junit public Addition(SampleClass sampleClassInterface) { super (); this .sampleClass = sampleClassInterface; }
  • 23. Example Contd….. public Addition() { super (); } public int add( int a, int b ){ int result = sampleClass.addition(a,b); return result; } public void setSampleClassInterface(SampleClassInterface sampleClassInterface) { this .sampleClass = sampleClassInterface; } }
  • 24. Why Coverage….?? Code coverage is a measure used in software testing . It describes the degree to which the source code of a program has been tested. It is a form of testing that inspects the code directly and is therefore a form of white box testing .
  • 25. Why Coverage…..?? Contd… Think about how you can focus around the developer and how Code Coverage can be used with Unit Testing. If you ask most developers if they do a good job testing their code, they would tell you yes. However in another study (Boris Beizer in Johnson 1994), the average programmer thought they tested around 95 percent of the code they wrote, but on further inspection the amount of actual code was more like 30 percent.
  • 26. Why Coverage Contd….. Developers are under more and more stress to deliver more code in less time. Automated code Generation tools used…. Big Question ??????? Do You Know Your Code……???
  • 27. Why Coverage Contd…. This information can be very enlightening. Think about it... you exercise your application with Code Coverage turned on and the results come back as 35 percent coverage. What's the deal? Did you just run your application with the &quot;happy path&quot; only or did you truly exercise the application? If you did exercise the application, then it appears a great deal of code may not be needed.
  • 28. Why Code Coverage…?? Another thing to keep in mind is the concept of condition’s in code. For each condition another test has to be written to properly test the other side of the condition. Again, if the testing is only focused on one path, then it is most likely &quot;happy path&quot; testing.
  • 29. Managers Boon… Once you get the use of Code Coverage down, it can be used for trending. This is very useful for program managers and companies as a whole.
  • 30. Managers Boon Contd….. For example, say that starting on week one we had 40 percent total coverage with unit test, week two we had 50 percent of coverage with unit tests, and week three we had 30 percent coverage with unit tests… what gives? Well from week three to four it may have been that the amount of code stayed about the same and more unit tests were created, and between weeks four and five a lot of code was added and very few unit tests were added.
  • 31. Code Coverage Tool EclEmma is a free Java code coverage tool for Eclipse, available under the Eclipse Public License. Internally it is based on the great EMMA Java code coverage tool, trying to adopt EMMA's philosophy for the Eclipse workbench: Fast develop/test cycle: Launches from within the workbench like JUnit test runs can directly be analyzed for code coverage.
  • 32. Code Coverage Tool Contd…… Rich coverage analysis: Coverage results are immediately summarized and highlighted in the Java source code editors. Non-invasive: EclEmma does not require modifying your projects or performing any other setup.
  • 33. Code Coverage Tool Contd…… Update Site for Eclipse 3.3 and Before Download the eclemma plugin….. Copy from features and plugins to the features and plugins of your eclipse…… Restart your eclipse through command line using eclipse –clean
  • 38. Thanks Happy Coding and Unit Testing.