SlideShare uma empresa Scribd logo
1 de 21
Junit 4.0

      -Pallavi Khandekar
What is JUnit?
• JUnit is an open source regression testing framework.

• Written by Erich Gamma and Kent Beck

• Part of xUnit family. (e.g. NUnit, CPPUnit etc)

• Eclipse includes JUnit. You can also run JUnit outside of
  Eclipse using JUnit’s window.

• Home page:
   – http://junit.org.
Unit Testing
• Key element in Extreme Programming.

• Focuses on fundamental block at a time.

• Helps to find problems early.

• Easy to maintain.

• Simplifies Integration testing.
Unit Testing (contn..)
• Proves as documentation of System(proves that
  system works).

• Leads to high quality code, higher productivity and
  low maintenance.

• JUnit helps developer write unit tests as they
  develop the system.

• Makes writing test cases easy and painless.
Application of JUnit:
        Test Driven Development (TDD)




TDD = TFD + Refactoring
Principles of testing frameworks.
• Each unit test should run independently of all other
  unit tests.

• Errors must be detected and reported test by test.

• It must be easy to define which unit tests will run.

• It should be easy to add unit tests.

• Help us reduce the cost of writing tests by reusing
  code.
Terminologies in Junit

                                     •A test case tests single method.
Runner                      Result
         Test Suite                  •A unit test tests all methods in a class.

             Unit Test 3             •A test suite combines unit test cases.

                                     • Test fixtures provide software support for all
             Unit Test 2             operations. (e.g. mock database)

                                     •The test runner runs the unit test or entire test
                                     suite.
             Unit Test 1
                                     •The test result collects & summarizes all test
                                     information of tests e.g. a test can pass , fail
            Test Fixtures            (assertion error) and error (exception is thrown)
Important Classes and Annotation of
         Junit Framework
Test : - Annotation that tells that the attached method is a test method.

Suite :- A class which runs all the unit test cases defined in @SuiteClasses
        annotation.

Assert:- Assert class provides lot of assert methods which we can use to throw an

        exception if the proposition to it fails.

Runner:- It runs a unit test/ suite and notifies RunNotifier of the significant

          event.

RunListener :- Listens to events triggered by Runner. (e.g. Test Begin, Test End etc)

Result:- Collects and summarizes all the information from multiple tests.
Annotations
Test Methods
Simple Case Study
• Create a Java project in Eclipse with two folders
   – src : will hold all the source code files
   – test: will hold all the test cases

• Write a method ‘multiply’ in Java class.
       /** This method multiplies the two integers.
        * @param x : first integer to be multiplied.
        * @param y : second integer to be multiplied.
        * @return integer product
        */
       public int multiply(int x, int y)
       {
          return x/y;
       }
Simple Case Study (cond..)

• Create a JUnit test case in ‘test’ folder . (File->
  New - > JUnit Test Case)

• Add method to test the ‘multiply’ method.
      @Test
      /**
       * test method to test Multiply functionality.
       */
      public void testMultiply() {
           MyFirstClass tester = new MyFirstClass();
           assertEquals("Result", 50, tester.multiply(5, 10));
      }
Simple Case Study (cond..)
• To execute the test case just right click and say Run as Junit
  test.


  The bar will be red if
  the test fails.


  It also displays in
  Failure trace the
  expected value and
  actual output of
  function in test.
Example 2
public class TestCounter {
     //Declare Counter
     Counter objCounter;                              Test class for Counter.
     @Before                                          Note*:
     public void setUp()
                                                      Each test begins with a brand new
     {
          objCounter = new Counter();                 Counter object. So for the
     }                                                decrement method we compared
                                                      return value with -1.
     @Test
     public void testIncrement() {                    Each tests are independent of each
          assertTrue(objCounter.increment() == 1);    other.
          assertTrue(objCounter.increment() == 2);
     }

     @Test
     public void testDecrement() {
          assertTrue(objCounter.decrement() == -1);
     }

}
public class Counter {
                              Example 2
                                   This is actual Counter Class.
     int intCounter = 0;

     //increament's counter
     public int increment(){
          return intCounter+=1;
     }

     //decreament's counter
     public int decrement(){
          return intCounter-=1;
     }

     //return's counter
     public int getIntCounter()
     {
          return intCounter;
     }

}
Expected Exception handling TestCases

    Method to test:                       Test Case
public class ArrayManipulations {         int[] a1= {1,2,3,4,5,6,7,8,9,10}; //length=10
                                          int[] b1= {0,2,4,6,8,10}; //length 6
public void Bar(int a[],int b[], int n)   @Test(expected =
  {                                       ArrayIndexOutOfBoundsException.class)
     a[0]=b[0];                           public void testBarPreconditions() {
     int i=1;                                   ArrayManipulations tester = new
     while (i<n) {                              ArrayManipulations();
           a[i]=b[i]+a[i-1];
           a[i-1]=0;                           int n = 11;
           i=i+1;                              tester.Bar(a1, b1, n);
     }                                    }
   }

}
Test Suites
                                                     • Test Suite is created from
import org.junit.runner.RunWith;                     New->Others->Junit->Junit Test
import org.junit.runners.Suite;                      Suite
import org.junit.runners.Suite.SuiteClasses;
                                                     •The suite will run all tests in
                                                     classes mentioned in
@RunWith(Suite.class)                                @SuiteClasses
@SuiteClasses({ MyTestClass.class, TestCounter.class })
public class AllTests {                                 •We can add on the .class
                                                        names whenever a new unit
}                                                       test is created.
Advantages of Junit framework
• Alternate front ends to display results of tests are available
  like command line, AWT and Swing.

• Separate class loaders for each unit test to avoid side
  effects.

• Provides methods like setUp and tearDown for standard
  resource initialization.

• A set of assert methods to check results of tests.

• Integration with popular tools such as Ant and Maven and
  IDE’s like Eclipse and Jbuilder.
Disadvantages of Junit Framework
• Cannot do dependency testing. TestNG allows this.

• Not suitable for higher level testing. (Large test suites.)
References
• http://junit.org.

• Javadoc: http://kentbeck.github.com/junit/javadoc/latest/

• Book: Junit in Action by Vincent Massol with Ted Husted
Thank You !!!

Questions ?

Mais conteúdo relacionado

Mais procurados (20)

Junit
JunitJunit
Junit
 
Unit testing with JUnit
Unit testing with JUnitUnit testing with JUnit
Unit testing with JUnit
 
Unit Testing
Unit TestingUnit Testing
Unit Testing
 
Unit Testing in Java
Unit Testing in JavaUnit Testing in Java
Unit Testing in Java
 
Unit Test Presentation
Unit Test PresentationUnit Test Presentation
Unit Test Presentation
 
Unit testing best practices
Unit testing best practicesUnit testing best practices
Unit testing best practices
 
Unit Tests And Automated Testing
Unit Tests And Automated TestingUnit Tests And Automated Testing
Unit Tests And Automated Testing
 
Junit
JunitJunit
Junit
 
Unit tests & TDD
Unit tests & TDDUnit tests & TDD
Unit tests & TDD
 
UNIT TESTING
UNIT TESTINGUNIT TESTING
UNIT TESTING
 
Mocking in Java with Mockito
Mocking in Java with MockitoMocking in Java with Mockito
Mocking in Java with Mockito
 
Understanding Unit Testing
Understanding Unit TestingUnderstanding Unit Testing
Understanding Unit Testing
 
JUnit 5
JUnit 5JUnit 5
JUnit 5
 
Defect life cycle and Defect Status Life Cycle
Defect life cycle and Defect Status Life CycleDefect life cycle and Defect Status Life Cycle
Defect life cycle and Defect Status Life Cycle
 
JUnit & Mockito, first steps
JUnit & Mockito, first stepsJUnit & Mockito, first steps
JUnit & Mockito, first steps
 
Unit testing with java
Unit testing with javaUnit testing with java
Unit testing with java
 
TestNG introduction
TestNG introductionTestNG introduction
TestNG introduction
 
Unit Testing
Unit TestingUnit Testing
Unit Testing
 
UNIT TESTING PPT
UNIT TESTING PPTUNIT TESTING PPT
UNIT TESTING PPT
 
Apache jMeter
Apache jMeterApache jMeter
Apache jMeter
 

Semelhante a Junit 4.0 (20)

Unit Testing - Nakov's Talk @ VarnaConf 2013
Unit Testing - Nakov's Talk @ VarnaConf 2013Unit Testing - Nakov's Talk @ VarnaConf 2013
Unit Testing - Nakov's Talk @ VarnaConf 2013
 
Unit testing by Svetlin Nakov
Unit testing by Svetlin NakovUnit testing by Svetlin Nakov
Unit testing by Svetlin Nakov
 
Junit
JunitJunit
Junit
 
Unit Testing with JUnit4 by Ravikiran Janardhana
Unit Testing with JUnit4 by Ravikiran JanardhanaUnit Testing with JUnit4 by Ravikiran Janardhana
Unit Testing with JUnit4 by Ravikiran Janardhana
 
8-testing.pptx
8-testing.pptx8-testing.pptx
8-testing.pptx
 
Test ng tutorial
Test ng tutorialTest ng tutorial
Test ng tutorial
 
Testing with Junit4
Testing with Junit4Testing with Junit4
Testing with Junit4
 
TestNG vs Junit
TestNG vs JunitTestNG vs Junit
TestNG vs Junit
 
Test ng
Test ngTest ng
Test ng
 
J unit presentation
J unit presentationJ unit presentation
J unit presentation
 
Test driven development
Test driven developmentTest driven development
Test driven development
 
Cpp unit
Cpp unit Cpp unit
Cpp unit
 
Junit With Eclipse
Junit With EclipseJunit With Eclipse
Junit With Eclipse
 
Junit
JunitJunit
Junit
 
Junit4&testng presentation
Junit4&testng presentationJunit4&testng presentation
Junit4&testng presentation
 
SE2018_Lec 20_ Test-Driven Development (TDD)
SE2018_Lec 20_ Test-Driven Development (TDD)SE2018_Lec 20_ Test-Driven Development (TDD)
SE2018_Lec 20_ Test-Driven Development (TDD)
 
SE2_Lec 21_ TDD and Junit
SE2_Lec 21_ TDD and JunitSE2_Lec 21_ TDD and Junit
SE2_Lec 21_ TDD and Junit
 
unit 1 (1).pptx
unit 1 (1).pptxunit 1 (1).pptx
unit 1 (1).pptx
 
Unit testing basics
Unit testing basicsUnit testing basics
Unit testing basics
 
3 j unit
3 j unit3 j unit
3 j unit
 

Último

Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...gurkirankumar98700
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...HostedbyConfluent
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 

Último (20)

Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 

Junit 4.0

  • 1. Junit 4.0 -Pallavi Khandekar
  • 2. What is JUnit? • JUnit is an open source regression testing framework. • Written by Erich Gamma and Kent Beck • Part of xUnit family. (e.g. NUnit, CPPUnit etc) • Eclipse includes JUnit. You can also run JUnit outside of Eclipse using JUnit’s window. • Home page: – http://junit.org.
  • 3. Unit Testing • Key element in Extreme Programming. • Focuses on fundamental block at a time. • Helps to find problems early. • Easy to maintain. • Simplifies Integration testing.
  • 4. Unit Testing (contn..) • Proves as documentation of System(proves that system works). • Leads to high quality code, higher productivity and low maintenance. • JUnit helps developer write unit tests as they develop the system. • Makes writing test cases easy and painless.
  • 5. Application of JUnit: Test Driven Development (TDD) TDD = TFD + Refactoring
  • 6. Principles of testing frameworks. • Each unit test should run independently of all other unit tests. • Errors must be detected and reported test by test. • It must be easy to define which unit tests will run. • It should be easy to add unit tests. • Help us reduce the cost of writing tests by reusing code.
  • 7. Terminologies in Junit •A test case tests single method. Runner Result Test Suite •A unit test tests all methods in a class. Unit Test 3 •A test suite combines unit test cases. • Test fixtures provide software support for all Unit Test 2 operations. (e.g. mock database) •The test runner runs the unit test or entire test suite. Unit Test 1 •The test result collects & summarizes all test information of tests e.g. a test can pass , fail Test Fixtures (assertion error) and error (exception is thrown)
  • 8. Important Classes and Annotation of Junit Framework Test : - Annotation that tells that the attached method is a test method. Suite :- A class which runs all the unit test cases defined in @SuiteClasses annotation. Assert:- Assert class provides lot of assert methods which we can use to throw an exception if the proposition to it fails. Runner:- It runs a unit test/ suite and notifies RunNotifier of the significant event. RunListener :- Listens to events triggered by Runner. (e.g. Test Begin, Test End etc) Result:- Collects and summarizes all the information from multiple tests.
  • 11. Simple Case Study • Create a Java project in Eclipse with two folders – src : will hold all the source code files – test: will hold all the test cases • Write a method ‘multiply’ in Java class. /** This method multiplies the two integers. * @param x : first integer to be multiplied. * @param y : second integer to be multiplied. * @return integer product */ public int multiply(int x, int y) { return x/y; }
  • 12. Simple Case Study (cond..) • Create a JUnit test case in ‘test’ folder . (File-> New - > JUnit Test Case) • Add method to test the ‘multiply’ method. @Test /** * test method to test Multiply functionality. */ public void testMultiply() { MyFirstClass tester = new MyFirstClass(); assertEquals("Result", 50, tester.multiply(5, 10)); }
  • 13. Simple Case Study (cond..) • To execute the test case just right click and say Run as Junit test. The bar will be red if the test fails. It also displays in Failure trace the expected value and actual output of function in test.
  • 14. Example 2 public class TestCounter { //Declare Counter Counter objCounter; Test class for Counter. @Before Note*: public void setUp() Each test begins with a brand new { objCounter = new Counter(); Counter object. So for the } decrement method we compared return value with -1. @Test public void testIncrement() { Each tests are independent of each assertTrue(objCounter.increment() == 1); other. assertTrue(objCounter.increment() == 2); } @Test public void testDecrement() { assertTrue(objCounter.decrement() == -1); } }
  • 15. public class Counter { Example 2 This is actual Counter Class. int intCounter = 0; //increament's counter public int increment(){ return intCounter+=1; } //decreament's counter public int decrement(){ return intCounter-=1; } //return's counter public int getIntCounter() { return intCounter; } }
  • 16. Expected Exception handling TestCases Method to test: Test Case public class ArrayManipulations { int[] a1= {1,2,3,4,5,6,7,8,9,10}; //length=10 int[] b1= {0,2,4,6,8,10}; //length 6 public void Bar(int a[],int b[], int n) @Test(expected = { ArrayIndexOutOfBoundsException.class) a[0]=b[0]; public void testBarPreconditions() { int i=1; ArrayManipulations tester = new while (i<n) { ArrayManipulations(); a[i]=b[i]+a[i-1]; a[i-1]=0; int n = 11; i=i+1; tester.Bar(a1, b1, n); } } } }
  • 17. Test Suites • Test Suite is created from import org.junit.runner.RunWith; New->Others->Junit->Junit Test import org.junit.runners.Suite; Suite import org.junit.runners.Suite.SuiteClasses; •The suite will run all tests in classes mentioned in @RunWith(Suite.class) @SuiteClasses @SuiteClasses({ MyTestClass.class, TestCounter.class }) public class AllTests { •We can add on the .class names whenever a new unit } test is created.
  • 18. Advantages of Junit framework • Alternate front ends to display results of tests are available like command line, AWT and Swing. • Separate class loaders for each unit test to avoid side effects. • Provides methods like setUp and tearDown for standard resource initialization. • A set of assert methods to check results of tests. • Integration with popular tools such as Ant and Maven and IDE’s like Eclipse and Jbuilder.
  • 19. Disadvantages of Junit Framework • Cannot do dependency testing. TestNG allows this. • Not suitable for higher level testing. (Large test suites.)
  • 20. References • http://junit.org. • Javadoc: http://kentbeck.github.com/junit/javadoc/latest/ • Book: Junit in Action by Vincent Massol with Ted Husted

Notas do Editor

  1. 1. It is designed for the purpose of writing and running tests in Java language.2. JUnit was originally written by Erich Gamma and Kent Beck3. Can be run through external interfaces like graphical swing test runner.
  2. We have learned in our lecture that Unit testing is a key element in the Extreme programming.It focuses on testing one fundamental block at a time rather than module level functional testing. This make code easy to maintainSimplifies Integration testing.
  3. It proves as a documentation of System.It improves the code quality, increases productivity and reduces the maintenance.The direct way to test some functionality in java is we write a method which passes some arguments to the method to be tested and then we print out the return value. But it is pain to write so many lines every time we want to test a method. Also when the output is printed multiple times on the screen it is hard to look at so many lines and identify whether a method runs correctly or not.Junit makes testing very easy and painless as we will see in next few slides.It also helps developer to write the unit tests in parallel with the development of a system.http://en.wikipedia.org/wiki/Unit_testing#Benefitshttp://googletesting.blogspot.com/2009/07/by-shyam-seshadri-nowadays-when-i-talk.html
  4. Junit is pretty widely used in Application which are build using Test Driven Development Approach.TDD = : first the developer writes an (initially failing) automated test case that defines a desired improvement or new function, then produces the minimum amount of code to pass that test and finally refactors the new code to acceptable standards
  5. These features are required in testing frameworks. Junit provides all these features.
  6. Test: This is an annotation which tells that the attached method is to test a unit program.Suite: Runs collection of TestCases from different Test Classes.Assert: This is a silent method. It throws an exception when if the proposition fails.Runner: It runs a test and notifies RunNotifier of the significant events.RunListener: Responds to any events triggered during test in progress. E.g. Test Begins, Test Ends, any failure or error.Result:It collects and summarizes all the information from running multiple tests. A test can Pass, Fail(Assertion Error) or has Error when an exception is thrown.
  7. @BeforeClass public static void init() { // Do one-time setup for all test cases } // init() @Before public void doSetup() { // Do setup before each test case } // setUp() @After public void doTearDown() { // Do tear down after each test case } // tearDown() @AfterClass public static void destroy() { // Do tear-down after all test cases are finished } // destroy() @Test public void testFactorial() {//Test methods.}
  8. All these methods are static methods.
  9. Eclipse comes with Junit
  10. @Test attribute denotes the test case.
  11. Junit view.
  12. We saw on previous slides that setUp method is called before each test method. So a brand new counter is assigned to each method.
  13. Interceptor-in 4.7 allows to expect multiple exceptions.
  14. Consider an example where I need to have Login details before any of the any access is made to database. TestNG:= is also a popular and well-known tool for testing Java. Next generation Java Testing.TestNG is especially useful with large test suites, where one test&apos;s failure shouldn&apos;t mean having to rerun a suite of thousands