SlideShare une entreprise Scribd logo
1  sur  32
Unit Testing with JUnit 4

       Ravikiran Janardhana


COMP 401: Foundations of Programming

          UNC – Chapel Hill
                                       1
Source: http://www.leonardscomic.com/comic/68/unit-testing/   2
Testing


Testing is the activity of finding out whether a
piece of code (method / program) produces
the intended behavior.




                                                   3
4
Testing phases
• Unit Testing on individual units of source
  code (mostly methods)

• Integration Testing on groups of individual
  software modules

• System testing on a complete end-to-end
  system
                                                5
Example: Assignment 2
• PolygonImpl
  – Create a polygon with „n‟ points
  – Compute area
  – Compute centroid



• How to test if the functionality implemented
  is correct ? Use JUnit

                                             6
Installing JUnit
• Eclipse users – You are in good shape. JUnit
  is already installed for you  !

• Caveat: Make sure you are using JUnit4
  instead of JUnit3, update if required

• Ubuntu - sudo apt-get install junit4




                                                 7
JUnit Demo Source Code
• JUnit Demo Source Code
  – Online (tiny url):
     http://bit.ly/XG97oO

  – Online (source) :
     https://docs.google.com/a/cs.unc.edu/file/d/0B3luEI_yhbZWMm
  RpQTlHS2pGNE0/edit?usp=sharing

  – Delete/Rename PolygonImplTest.java if you want to code it
    during this session




                                                                8
Creating a new JUnit TestCase




                                9
Creating a new JUnit TestCase




                                10
Creating a new JUnit TestCase




                                11
Testing in JUnit
• Tests are written as “public void testX()”
  methods (good practice).

• Use @Test annotation to mark a method
  as a test case. (compulsory)

• Annotations provide data about a program
  that is not part of the program itself.
                                               12
Annotations
• @Test – mark a method as test

• @BeforeClass – run once before all tests

• @AfterClass – run once after all tests

• @Before – called before every testX()

• @After – called after every testX()

                                             13
14
Part I : Initialize
package demo;

import static org.junit.Assert.assertEquals;

import   org.junit.After;
import   org.junit.AfterClass;
import   org.junit.Before;
import   org.junit.BeforeClass;
import   org.junit.Test;

public class PolygonImplTest{
      private PolygonImpl p;

         // One Time Setup
         @BeforeClass
         public void runOnceBeforeAllTests(){

         }
         // Tear down after all tests
         @AfterClass
         public void runAfterAllTests(){

         }

                                                15
Part I : Initialize (Setup)
// Creates test environment (fixture).
// Called before every testX() method.
@Before
public void setUp() throws Exception {
       Point a = new Point(-1, -2);
       Point b = new Point(-2.5, -3.5);
       Point c = new Point(-3.1, -1.4);
       Point d = new Point(-2, 1.3);
       Point e = new Point(1, 1);
       Point f = new Point(2, 3);
       Point g = new Point(3, 0.5);
       Point h = new Point(5, 2.5);
       Point i = new Point(4, -2);
       Point j = new Point(1.5, -1.5);

      Point[] poly_points = new Point[] {a, b, c, d, e, f, g, h, i, j};
      this.p = new PolygonImpl(poly_points)
}                                                                     16
Part I : Initialize (Tear Down)
// Releases test environment (fixture).
// Called after every testX() method.
@After
public void tearDown() throws Exception {
       p = null;
}




                                            17
Part II: Write Test Cases
• Helper methods to test:

  fail(msg) – triggers a failure named msg

  assertTrue(msg, b) – triggers a failure, when condition b is false

  assertEquals(msg, v1, v2) – triggers a failure, when v1 == v2 is false   ✓
  assertEquals(msg, v1, v2, eps) – triggers a failure, if abs(v1 – v2) > eps   ✓
  assertNull(msg, object) – triggers a failure, when object is not null

  assertNonNull(msg, object) – triggers a failure, when object is null

                   The parameter msg is optional                               18
Test getArea() and getCentroid()
@Test
public void testPolygonArea() {
       assertEquals("P1: polygon area is wrong", p.getArea(), 24.24, 0.01);
}

@Test
public void testPolygonCentroid() {
       Point centroid = p.getCentroid();
       assertEquals("P2: centroid (x) is wrong", centroid.getX(), 0.7646, 0.01);
       assertEquals("P2: centroid (y) is wrong", centroid.getY(), -0.3067, 0.01);

      //The below assertion will print an AssertionFailedError, can you tell me
      why ?
      //But it may also pass with some modification to Point class
      assertEquals("P2: centroid is wrong", p.getCentroid(), new Point(0.7646,
      -0.3067));
}



                                                                                  19
Junit Test Result




Source: www.lordoftherings.net
                                 20
Junit Test Result




• The “==“ operator compares the reference of the variable.

• To fix it, override the Object.equals() method in Point
  class.
                                                              21
Override equals()
@Override
public boolean equals(Object obj){ //Parameter is of type Object
    if(obj == null) return false;
    if(obj == this) return true;
    if(!(obj instanceof Point)) return false;

    Point q = (Point) obj;
    if(Math.abs(this.getX() - q.getX()) < 0.01 &&
       Math.abs(this.getY() - q.getY()) < 0.01){
           return true;
    }
    return false;
}


                                                              22
Junit Test Result




                    23
Part III : Writing a Test Suite
• In JUnit 3.8, you had to add a suite() method to
  your classes to run all tests as a suite.

• With JUnit 4.0, you can use annotations instead.

• To run the PolygonImplTest, you write an empty
  class with @RunWith and @Suite annotations.

• Very useful when you need to batch and run all the
  test classes in one shot.

                                                     24
Part III : All tests in one shot
package demo;

import org.junit.runner.RunWith;
import org.junit.runners.Suite;

@RunWith(Suite.class)
@Suite.SuiteClasses({PolygonImplTest.class})
public class PolygonImplTestSuite {
     //Empty Class
}




                                               25
Part IV: Executing Tests
• Eclipse – Ctrl + F11 (run), F11 (debug)

• Command line

[ravikirn@xps demo]# javac -cp /usr/share/java/junit4.jar PolygonImpl.java Polygon.java
Point.java PolygonImplTest.java

[ravikirn@xps src]# java -cp /usr/share/java/junit4.jar:. org.junit.runner.JUnitCore
demo.PolygonImplTest




                                                                                          26
Eclipse
• Auto resolve package dependency
  – Ctrl + Shift + O

• Auto format code (helps when you paste
  non-formatted code)
  – Ctrl + Shift + F

• vim-like editing in Eclipse - vrapper


                                           27
vim / emacs




  • Trust me, it‟s totally worth learning vim / emacs
  • http://www.openvim.com/tutorial.html
  • http://www.derekwyatt.org/vim/vim-tutorial-videos/

img source: http://www.thejach.com/view/2012/07/vims_learning_curve_is_wrong   28
Best Practices
• Test Everything that can possibly break.

• Test I/O, nulls and boundary conditions,
  they are always the big culprits.

• Test Driven Development (TDD)
  – TestCase  Code  Pass Test  Refactor


                                             29
Summary
• Testing                  • Self Study / Explore
   – Unit Testing             – How to test private and
   – Integration Testing        protected methods?
   – System Testing
                              – How to test methods which
                                take input from console
• Junit                         (and | or) dump output to
   – Initialize                 console ?
   – Write Test Cases
   – Batch Test Cases         – How to test methods that
     (TestSuite)                don‟t return or print
   – Execute Test Case          anything to the console ?

                              – How to test exceptions ?
                                                            30
31
Q&A




Many of the slides are attributed to Thomas Zimmermann
                                                         32

Contenu connexe

Tendances

Simple Unit Testing With Netbeans 6.1
Simple Unit Testing With Netbeans 6.1Simple Unit Testing With Netbeans 6.1
Simple Unit Testing With Netbeans 6.1Kiki Ahmadi
 
Introduction To J unit
Introduction To J unitIntroduction To J unit
Introduction To J unitOlga Extone
 
JUnit 5 - The Next Generation of JUnit - Ted's Tool Time
JUnit 5 - The Next Generation of JUnit - Ted's Tool TimeJUnit 5 - The Next Generation of JUnit - Ted's Tool Time
JUnit 5 - The Next Generation of JUnit - Ted's Tool TimeTed Vinke
 
Unit testing with Junit
Unit testing with JunitUnit testing with Junit
Unit testing with JunitValerio Maggio
 
Test driven development - JUnit basics and best practices
Test driven development - JUnit basics and best practicesTest driven development - JUnit basics and best practices
Test driven development - JUnit basics and best practicesNarendra Pathai
 
What is JUnit? | Edureka
What is JUnit? | EdurekaWhat is JUnit? | Edureka
What is JUnit? | EdurekaEdureka!
 
Unit testing best practices
Unit testing best practicesUnit testing best practices
Unit testing best practicesnickokiss
 
Advanced junit and mockito
Advanced junit and mockitoAdvanced junit and mockito
Advanced junit and mockitoMathieu Carbou
 

Tendances (20)

Unit testing with JUnit
Unit testing with JUnitUnit testing with JUnit
Unit testing with JUnit
 
Java Unit Testing
Java Unit TestingJava Unit Testing
Java Unit Testing
 
Junit
JunitJunit
Junit
 
3 j unit
3 j unit3 j unit
3 j unit
 
JUnit 5
JUnit 5JUnit 5
JUnit 5
 
JUNit Presentation
JUNit PresentationJUNit Presentation
JUNit Presentation
 
Unit testing with JUnit
Unit testing with JUnitUnit testing with JUnit
Unit testing with JUnit
 
Simple Unit Testing With Netbeans 6.1
Simple Unit Testing With Netbeans 6.1Simple Unit Testing With Netbeans 6.1
Simple Unit Testing With Netbeans 6.1
 
JUnit Presentation
JUnit PresentationJUnit Presentation
JUnit Presentation
 
Introduction To J unit
Introduction To J unitIntroduction To J unit
Introduction To J unit
 
JUnit 5 - The Next Generation of JUnit - Ted's Tool Time
JUnit 5 - The Next Generation of JUnit - Ted's Tool TimeJUnit 5 - The Next Generation of JUnit - Ted's Tool Time
JUnit 5 - The Next Generation of JUnit - Ted's Tool Time
 
J Unit
J UnitJ Unit
J Unit
 
Unit testing with Junit
Unit testing with JunitUnit testing with Junit
Unit testing with Junit
 
Test driven development - JUnit basics and best practices
Test driven development - JUnit basics and best practicesTest driven development - JUnit basics and best practices
Test driven development - JUnit basics and best practices
 
What is JUnit? | Edureka
What is JUnit? | EdurekaWhat is JUnit? | Edureka
What is JUnit? | Edureka
 
Junit
JunitJunit
Junit
 
Unit testing best practices
Unit testing best practicesUnit testing best practices
Unit testing best practices
 
Advanced junit and mockito
Advanced junit and mockitoAdvanced junit and mockito
Advanced junit and mockito
 
JUnit Pioneer
JUnit PioneerJUnit Pioneer
JUnit Pioneer
 
Why Unit Testingl
Why Unit TestinglWhy Unit Testingl
Why Unit Testingl
 

En vedette

En vedette (7)

Test Driven Development and JUnit
Test Driven Development and JUnitTest Driven Development and JUnit
Test Driven Development and JUnit
 
Log4 J
Log4 JLog4 J
Log4 J
 
Junit and testNG
Junit and testNGJunit and testNG
Junit and testNG
 
JUnit 5 - from Lambda to Alpha and beyond
JUnit 5 - from Lambda to Alpha and beyondJUnit 5 - from Lambda to Alpha and beyond
JUnit 5 - from Lambda to Alpha and beyond
 
JUnit & Mockito, first steps
JUnit & Mockito, first stepsJUnit & Mockito, first steps
JUnit & Mockito, first steps
 
Mockito
MockitoMockito
Mockito
 
Mocking in Java with Mockito
Mocking in Java with MockitoMocking in Java with Mockito
Mocking in Java with Mockito
 

Similaire à Unit Testing with JUnit4 by Ravikiran Janardhana

J unit presentation
J unit presentationJ unit presentation
J unit presentationPriya Sharma
 
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 2013Svetlin Nakov
 
Unit testing by Svetlin Nakov
Unit testing by Svetlin NakovUnit testing by Svetlin Nakov
Unit testing by Svetlin Nakovit-tour
 
Game Programming 06 - Automated Testing
Game Programming 06 - Automated TestingGame Programming 06 - Automated Testing
Game Programming 06 - Automated TestingNick Pruehs
 
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)Amr E. Mohamed
 
Fu agile#2 unit_testing
Fu agile#2 unit_testingFu agile#2 unit_testing
Fu agile#2 unit_testingNguyen Anh
 
Lecture (Software Testing).pptx
Lecture (Software Testing).pptxLecture (Software Testing).pptx
Lecture (Software Testing).pptxskknowledge
 
SE2_Lec 21_ TDD and Junit
SE2_Lec 21_ TDD and JunitSE2_Lec 21_ TDD and Junit
SE2_Lec 21_ TDD and JunitAmr E. Mohamed
 
Software Testing - Invited Lecture at UNSW Sydney
Software Testing - Invited Lecture at UNSW SydneySoftware Testing - Invited Lecture at UNSW Sydney
Software Testing - Invited Lecture at UNSW Sydneyjulien.ponge
 
Introduction to JUnit testing in OpenDaylight
Introduction to JUnit testing in OpenDaylightIntroduction to JUnit testing in OpenDaylight
Introduction to JUnit testing in OpenDaylightOpenDaylight
 

Similaire à Unit Testing with JUnit4 by Ravikiran Janardhana (20)

8-testing.pptx
8-testing.pptx8-testing.pptx
8-testing.pptx
 
J unit presentation
J unit presentationJ unit presentation
J unit presentation
 
Junit With Eclipse
Junit With EclipseJunit With Eclipse
Junit With Eclipse
 
Test ng tutorial
Test ng tutorialTest ng tutorial
Test ng tutorial
 
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
 
Game Programming 06 - Automated Testing
Game Programming 06 - Automated TestingGame Programming 06 - Automated Testing
Game Programming 06 - Automated Testing
 
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)
 
Test ng
Test ngTest ng
Test ng
 
Test driven development
Test driven developmentTest driven development
Test driven development
 
Python testing
Python  testingPython  testing
Python testing
 
Fu agile#2 unit_testing
Fu agile#2 unit_testingFu agile#2 unit_testing
Fu agile#2 unit_testing
 
TestNG vs Junit
TestNG vs JunitTestNG vs Junit
TestNG vs Junit
 
Lecture (Software Testing).pptx
Lecture (Software Testing).pptxLecture (Software Testing).pptx
Lecture (Software Testing).pptx
 
SE2_Lec 21_ TDD and Junit
SE2_Lec 21_ TDD and JunitSE2_Lec 21_ TDD and Junit
SE2_Lec 21_ TDD and Junit
 
Software Testing - Invited Lecture at UNSW Sydney
Software Testing - Invited Lecture at UNSW SydneySoftware Testing - Invited Lecture at UNSW Sydney
Software Testing - Invited Lecture at UNSW Sydney
 
Introduction to JUnit testing in OpenDaylight
Introduction to JUnit testing in OpenDaylightIntroduction to JUnit testing in OpenDaylight
Introduction to JUnit testing in OpenDaylight
 
Python unit testing
Python unit testingPython unit testing
Python unit testing
 
Junit_.pptx
Junit_.pptxJunit_.pptx
Junit_.pptx
 
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven Development
 

Dernier

ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...JojoEDelaCruz
 
Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4JOYLYNSAMANIEGO
 
Integumentary System SMP B. Pharm Sem I.ppt
Integumentary System SMP B. Pharm Sem I.pptIntegumentary System SMP B. Pharm Sem I.ppt
Integumentary System SMP B. Pharm Sem I.pptshraddhaparab530
 
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONHumphrey A Beña
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Celine George
 
Active Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdfActive Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdfPatidar M
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatYousafMalik24
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Mark Reed
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxiammrhaywood
 
ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4MiaBumagat1
 
Activity 2-unit 2-update 2024. English translation
Activity 2-unit 2-update 2024. English translationActivity 2-unit 2-update 2024. English translation
Activity 2-unit 2-update 2024. English translationRosabel UA
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxHumphrey A Beña
 
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptxQ4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptxlancelewisportillo
 
4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptx4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptxmary850239
 
ROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxVanesaIglesias10
 
Karra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxKarra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxAshokKarra1
 
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfVirtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfErwinPantujan2
 
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfGrade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfJemuel Francisco
 

Dernier (20)

ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
 
Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4
 
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptxYOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
 
Integumentary System SMP B. Pharm Sem I.ppt
Integumentary System SMP B. Pharm Sem I.pptIntegumentary System SMP B. Pharm Sem I.ppt
Integumentary System SMP B. Pharm Sem I.ppt
 
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17
 
Active Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdfActive Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdf
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice great
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
 
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptxFINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
 
ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4
 
Activity 2-unit 2-update 2024. English translation
Activity 2-unit 2-update 2024. English translationActivity 2-unit 2-update 2024. English translation
Activity 2-unit 2-update 2024. English translation
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
 
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptxQ4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
 
4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptx4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptx
 
ROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptx
 
Karra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxKarra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptx
 
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfVirtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
 
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfGrade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
 

Unit Testing with JUnit4 by Ravikiran Janardhana

  • 1. Unit Testing with JUnit 4 Ravikiran Janardhana COMP 401: Foundations of Programming UNC – Chapel Hill 1
  • 3. Testing Testing is the activity of finding out whether a piece of code (method / program) produces the intended behavior. 3
  • 4. 4
  • 5. Testing phases • Unit Testing on individual units of source code (mostly methods) • Integration Testing on groups of individual software modules • System testing on a complete end-to-end system 5
  • 6. Example: Assignment 2 • PolygonImpl – Create a polygon with „n‟ points – Compute area – Compute centroid • How to test if the functionality implemented is correct ? Use JUnit 6
  • 7. Installing JUnit • Eclipse users – You are in good shape. JUnit is already installed for you  ! • Caveat: Make sure you are using JUnit4 instead of JUnit3, update if required • Ubuntu - sudo apt-get install junit4 7
  • 8. JUnit Demo Source Code • JUnit Demo Source Code – Online (tiny url): http://bit.ly/XG97oO – Online (source) : https://docs.google.com/a/cs.unc.edu/file/d/0B3luEI_yhbZWMm RpQTlHS2pGNE0/edit?usp=sharing – Delete/Rename PolygonImplTest.java if you want to code it during this session 8
  • 9. Creating a new JUnit TestCase 9
  • 10. Creating a new JUnit TestCase 10
  • 11. Creating a new JUnit TestCase 11
  • 12. Testing in JUnit • Tests are written as “public void testX()” methods (good practice). • Use @Test annotation to mark a method as a test case. (compulsory) • Annotations provide data about a program that is not part of the program itself. 12
  • 13. Annotations • @Test – mark a method as test • @BeforeClass – run once before all tests • @AfterClass – run once after all tests • @Before – called before every testX() • @After – called after every testX() 13
  • 14. 14
  • 15. Part I : Initialize package demo; import static org.junit.Assert.assertEquals; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; public class PolygonImplTest{ private PolygonImpl p; // One Time Setup @BeforeClass public void runOnceBeforeAllTests(){ } // Tear down after all tests @AfterClass public void runAfterAllTests(){ } 15
  • 16. Part I : Initialize (Setup) // Creates test environment (fixture). // Called before every testX() method. @Before public void setUp() throws Exception { Point a = new Point(-1, -2); Point b = new Point(-2.5, -3.5); Point c = new Point(-3.1, -1.4); Point d = new Point(-2, 1.3); Point e = new Point(1, 1); Point f = new Point(2, 3); Point g = new Point(3, 0.5); Point h = new Point(5, 2.5); Point i = new Point(4, -2); Point j = new Point(1.5, -1.5); Point[] poly_points = new Point[] {a, b, c, d, e, f, g, h, i, j}; this.p = new PolygonImpl(poly_points) } 16
  • 17. Part I : Initialize (Tear Down) // Releases test environment (fixture). // Called after every testX() method. @After public void tearDown() throws Exception { p = null; } 17
  • 18. Part II: Write Test Cases • Helper methods to test: fail(msg) – triggers a failure named msg assertTrue(msg, b) – triggers a failure, when condition b is false assertEquals(msg, v1, v2) – triggers a failure, when v1 == v2 is false ✓ assertEquals(msg, v1, v2, eps) – triggers a failure, if abs(v1 – v2) > eps ✓ assertNull(msg, object) – triggers a failure, when object is not null assertNonNull(msg, object) – triggers a failure, when object is null The parameter msg is optional 18
  • 19. Test getArea() and getCentroid() @Test public void testPolygonArea() { assertEquals("P1: polygon area is wrong", p.getArea(), 24.24, 0.01); } @Test public void testPolygonCentroid() { Point centroid = p.getCentroid(); assertEquals("P2: centroid (x) is wrong", centroid.getX(), 0.7646, 0.01); assertEquals("P2: centroid (y) is wrong", centroid.getY(), -0.3067, 0.01); //The below assertion will print an AssertionFailedError, can you tell me why ? //But it may also pass with some modification to Point class assertEquals("P2: centroid is wrong", p.getCentroid(), new Point(0.7646, -0.3067)); } 19
  • 20. Junit Test Result Source: www.lordoftherings.net 20
  • 21. Junit Test Result • The “==“ operator compares the reference of the variable. • To fix it, override the Object.equals() method in Point class. 21
  • 22. Override equals() @Override public boolean equals(Object obj){ //Parameter is of type Object if(obj == null) return false; if(obj == this) return true; if(!(obj instanceof Point)) return false; Point q = (Point) obj; if(Math.abs(this.getX() - q.getX()) < 0.01 && Math.abs(this.getY() - q.getY()) < 0.01){ return true; } return false; } 22
  • 24. Part III : Writing a Test Suite • In JUnit 3.8, you had to add a suite() method to your classes to run all tests as a suite. • With JUnit 4.0, you can use annotations instead. • To run the PolygonImplTest, you write an empty class with @RunWith and @Suite annotations. • Very useful when you need to batch and run all the test classes in one shot. 24
  • 25. Part III : All tests in one shot package demo; import org.junit.runner.RunWith; import org.junit.runners.Suite; @RunWith(Suite.class) @Suite.SuiteClasses({PolygonImplTest.class}) public class PolygonImplTestSuite { //Empty Class } 25
  • 26. Part IV: Executing Tests • Eclipse – Ctrl + F11 (run), F11 (debug) • Command line [ravikirn@xps demo]# javac -cp /usr/share/java/junit4.jar PolygonImpl.java Polygon.java Point.java PolygonImplTest.java [ravikirn@xps src]# java -cp /usr/share/java/junit4.jar:. org.junit.runner.JUnitCore demo.PolygonImplTest 26
  • 27. Eclipse • Auto resolve package dependency – Ctrl + Shift + O • Auto format code (helps when you paste non-formatted code) – Ctrl + Shift + F • vim-like editing in Eclipse - vrapper 27
  • 28. vim / emacs • Trust me, it‟s totally worth learning vim / emacs • http://www.openvim.com/tutorial.html • http://www.derekwyatt.org/vim/vim-tutorial-videos/ img source: http://www.thejach.com/view/2012/07/vims_learning_curve_is_wrong 28
  • 29. Best Practices • Test Everything that can possibly break. • Test I/O, nulls and boundary conditions, they are always the big culprits. • Test Driven Development (TDD) – TestCase  Code  Pass Test  Refactor 29
  • 30. Summary • Testing • Self Study / Explore – Unit Testing – How to test private and – Integration Testing protected methods? – System Testing – How to test methods which take input from console • Junit (and | or) dump output to – Initialize console ? – Write Test Cases – Batch Test Cases – How to test methods that (TestSuite) don‟t return or print – Execute Test Case anything to the console ? – How to test exceptions ? 30
  • 31. 31
  • 32. Q&A Many of the slides are attributed to Thomas Zimmermann 32