SlideShare ist ein Scribd-Unternehmen logo
1 von 33
Downloaden Sie, um offline zu lesen
Software Testing
- Test Driven Development
    (TDD) with JUnit -

Fernando Brito e Abreu
DCTI / ISCTE-IUL
QUASAR Research Group
SWEBOK: the 10 Knowledge Areas
   Software Requirements
   Software Design
   Software Construction
   Software Testing
   Software Maintenance
   Software Configuration Management
   Software Engineering Management
   Software Engineering Process
   Software Engineering Tools and Methods
   Software Quality
27-Sep-11          Software Engineering / Fernando Brito e Abreu   2
Working test first / TDD
   Traditionally, code has been written using a
    test-last philosophy, i.e. design, code, then test
   Testing after the fact is often boring
   Write code “test first” instead:
        Write a simple test (one assertion)
        Write enough code to make the test pass

     Repeat the process, ‘filling’ out the code


27-Sep-11            Software Engineering / Fernando Brito e Abreu   3
Unit testing, extreme style
   Tests should be an integral part of the coding
    process

   Whenever you implement a class, also make a
    companion test class

   Tests are executable documentation
      Testsallow other programmers see how to use code
      Therefore they are part of the specification


27-Sep-11          Software Engineering / Fernando Brito e Abreu   4
Best practices
   Test everything that could possibly break
      This      is an XP maxim and it holds


   A well-written test is hard to pass
      If    all your tests pass the first time, you are probably
            not testing vigorously enough


   All tests should pass before any update is made
    to a collective code base
27-Sep-11                 Software Engineering / Fernando Brito e Abreu   5
Best practices
   When a test case fails, track down the problem
    by writing more tests, before going to the
    debugger
      The      more tests you have, the better


   Test invalid parameters to every method, rather
    than just valid data
      Robust        software needs to recognize and handle
            invalid data, and the tests that pass using incorrect
            data are often the most informative
27-Sep-11                 Software Engineering / Fernando Brito e Abreu   6
The xUnit testing frameworks story
   Kent Beck published a unit test framework for the
    Smalltalk language in 1999 named SmalltalkUnit (aka
    SUnit)

   Later, Erich Gamma ported SUnit to Java, creating JUnit

   Many more xUnit implementations adapted to various
    languages and platforms were made since
     CppUnit   (C++), NUnit (.Net), Dunit (Delphi), VBUnit (Visual
       Basic), RUnit (R), PyUnit (Pyton), HtmlUnit, XMLUnit, …


27-Sep-11                Software Engineering / Fernando Brito e Abreu   7
JUnit for Eclipse

                                                                               Test class




                                         This bar is only green
                                         when all tests pass!




Test error messages and
tracing info appear here
27-Sep-11 selected test case
for the                        Software Engineering / Fernando Brito e Abreu                8
Building a test suite
   A test suite is the union of the test cases for all classes
    in the system

   A test suite should have:
      One      test class for each class in the system


   Each test class should have at least one test method
    (aka test case) for each method in the class under test
      To      be more precise, we should have a number of test cases
            given by the McCabe complexity metric of the target method

27-Sep-11                  Software Engineering / Fernando Brito e Abreu   9
Test case stubs
   JUnit test case stubs can be generated with Eclipse
      Since       only one test case stub is generated per method, you
            should cut and paste those stubs if McCabe complexity metric
            is greater than one


   Method stubs look like this:

            @Test
            public final void testSomeMethod()
            {
              fail("Not yet implemented"); // TODO
            }


27-Sep-11                        Software Engineering / Fernando Brito e Abreu   10
Test case stubs                                             Here we choose which
                                                            stubs we want to create




27-Sep-11   Software Engineering / Fernando Brito e Abreu                             11
Test suite organization
   Test code must be separated from application
     Give  them each their own unique directory tree with
       the same package naming structure
             One tree using “src” as root
             Another tree using “tests” as root




     This   lets tests live in the same package as the objects
       they test, while still keeping them separate during a
       build


27-Sep-11                   Software Engineering / Fernando Brito e Abreu   12
Test suite organization




            If you select a directory and do “Run As
            / Junit Test” all test classes contained in
            it (recursively) are executed.


            If you select a file and do “Run As / Junit
            Test” only the test cases in it are executed.

27-Sep-11        Software Engineering / Fernando Brito e Abreu   13
This convention is just an
Naming convention                                                   example. The important thing is
                                                                    using a consistent convention
                                                                    to facilitate maintainability.
   Test classes
      <test      class name> ::= <class name>Test
               e.g. ClientAccountTest, CurrencyTest, …


   Test cases
      <test      case name> ::= test[<n>]<method name>.java
               The <n> counter can be discarded when we have a single test (McCabe
                complexity = 1)
               e.g. client.testgetName(), myAccount.test1deposit(),
                myAccount.test2deposit(), …




27-Sep-11                      Software Engineering / Fernando Brito e Abreu                          14
JUnit mechanisms
   Annotations
      The      mechanism by which JUnit determines organizes
            and activates your test cases


   Assertions
      The mechanism by which JUnit determines the
       success or failure of a test
      An assert is a comparison between an expected
       value and an actual value

27-Sep-11               Software Engineering / Fernando Brito e Abreu   15
Annotations
 @BeforeClass
 @AfterClass
 @Before
 @After
 @Test
 @Ignore
 @Timeout



27-Sep-11    Software Engineering / Fernando Brito e Abreu   16
@BeforeClass
   This annotation allows setting up methods that will run
    before the full test suite contained in the class
   This can be used to perform time intensive activities
     Example:   connect to a database
                                                There is no restriction on the names of
                                                the methods, but you should use
                                                semantically meaningful identifiers

            @BeforeClass
            public void runBeforeFullSuite() {
                    // run once before all test cases
            }


27-Sep-11                Software Engineering / Fernando Brito e Abreu                    17
@AfterClass
   This annotation allows setting up methods that will run
    after all tests contained in the class have finished
   This can be used to perform clean-up activities
     Example:     disconnect from a database


            @AfterClass
            public void runAfterFullSuite() {
                    // run for one time after all test cases
            }




27-Sep-11                   Software Engineering / Fernando Brito e Abreu   18
@Before
   This annotation allows setting up all test cases, since the
    corresponding method will run before each test case
   A @Before method can prepare the test environment
     e.g.   read input data, initialize the class


                @Before
                public void runBeforeEveryTest() {
                  simpleMath = new SimpleMath();
                }




27-Sep-11                  Software Engineering / Fernando Brito e Abreu   19
@After
   This annotation allows tearing down test methods since
    it will run after every test case


            @After
            public void runAfterEveryTest() {
              simpleMath = null;
            }




27-Sep-11              Software Engineering / Fernando Brito e Abreu   20
@Test
   Mark your test cases with @Test annotations
   You don’t need to prefix your test cases with “test”,
    although this is a good naming convention

             @Test
             public void testAddition() {
                 assertEquals(12, simpleMath.add(7, 5));
             }

             @Test
               public void testSubtraction() {
               assertEquals(9, simpleMath.subtract(12, 3));
             }

27-Sep-11               Software Engineering / Fernando Brito e Abreu   21
@Test
   Another example:

            @Test
            public void listEquality() {
              List<Integer> expected = new ArrayList<Integer>();
              expected.add(5);

                List<Integer> actual = new ArrayList<Integer>();
                actual.add(5);

                assertEquals(expected, actual);
            }



27-Sep-11                     Software Engineering / Fernando Brito e Abreu   22
@Test(timeout = <delay>)
   Define a timeout period in milliseconds with “timeout”
    parameter
   The test fails when the timeout period exceeds

            @Test(timeout = 1000)
            public void infinity() {
              while (true)
                 ;
            }




27-Sep-11                 Software Engineering / Fernando Brito e Abreu   23
@Test(expected = <exception>.class)
   Tests succeeds if the method throws the exception




                                         Notice that the fail command is not executed
                                         because the exception is raised and caught
                                         by JUnit, that sees any further.
27-Sep-11           Software Engineering / Fernando Brito e Abreu                       24
@Ignore
   Use this annotation for test cases you want to ignore
     You   can add a string parameter that defines the reason of
       ignorance
   This may be useful if the underlying code has been changed and
    the test has not yet been adapted


             @Ignore("Not Ready to Run")
             @Test
             public void multiplication() {
               assertEquals(15, simpleMath.multiply(3, 5));
             }


27-Sep-11               Software Engineering / Fernando Brito e Abreu   25
Assertions
 assertEquals
 assertEquals for arrays
 assertNull / assertNotNull
 assertSame / assertNotSame
 assertTrue / assertFalse
 fail




27-Sep-11     Software Engineering / Fernando Brito e Abreu   26
assertEquals
      This assertion states that:
        expected.equals(actual)          returns true, or
        both   objects are null
      A message is printed if supplied, when a test fails
      The equality test for a double or a float should specify
       a maximum tolerance range (the delta), to cope with
       floating point errors
      There are overloaded versions of this method for all
       Java’s primitive types
  assertEquals(Object expected, Object actual)
  assertEquals(String message, Object expected, Object actual)
  assertEquals(Object expected, Object actual, delta)
  assertEquals(String message, Engineering /expected, eObject actual, delta)
27-Sep-11                Software Object Fernando Brito Abreu                  27
assertEquals for arrays
       Two arrays are equal if they have the same length and
        each element is equal to the corresponding element in
        the other array; otherwise, they’re not.

public static void assertEquals(Object[] expected, Object[] actual);
public static void assertEquals(String message, Object[] expected, Object[]
actual);




27-Sep-11                Software Engineering / Fernando Brito e Abreu        28
assertNull / assertNotNull
       This asserts that an object reference equals null,
        printing a message otherwise (if supplied)
               assertNull(Object object),
               assertNull(String message, Object object)



       This asserts that an object reference is not null,
        printing a message otherwise (if supplied)

                 assertNotNull(Object object),
                 assertNotNull(String message, Object)


27-Sep-11               Software Engineering / Fernando Brito e Abreu   29
assertSame / assertNotSame
       Asserts that the two objects are the same, printing a
        message otherwise (if supplied)
             Thisis a stricter condition than simple equality, as it
               compares the object identities using expected == actual

            assertSame(Object expected, Object actual)
            assertSame(String message, Object expected, Object actual)


       Asserts that the two objects are not the same,
        printing a message otherwise (if supplied)
             assertNotSame(Object expected, Object actual)
             assertNotSame(String message, Object expected, Object actual)
27-Sep-11                     Software Engineering / Fernando Brito e Abreu   30
assertTrue / assertFalse
       Asserts that the condition is true, printing a message
        otherwise (if supplied)
            assertTrue(boolean condition)
            assertTrue(String message, boolean condition)



       Asserts that the condition is false, printing a message
        otherwise (if supplied)
            assertFalse(boolean condition)
            assertFalse(String message, boolean condition)



27-Sep-11                     Software Engineering / Fernando Brito e Abreu   31
fail

   This forces a failure. This is useful to close off paths
    through the code that should not be reached

            fail()
            fail(String message)




27-Sep-11                     Software Engineering / Fernando Brito e Abreu   32
More Reading
   http://www.junit.org/index.htm
   http://open.ncsu.edu/se/tutorials/junit/
   http://www.cs.umanitoba.ca/~eclipse/10-JUnit.pdf
   http://supportweb.cs.bham.ac.uk/documentation/tutorial
    s/docsystem/build/tutorials/junit/junit.pdf
   http://junit.sourceforge.net/javadoc/junit/framework/




27-Sep-11           Software Engineering / Fernando Brito e Abreu   33

Weitere ähnliche Inhalte

Was ist angesagt?

Unit testing best practices
Unit testing best practicesUnit testing best practices
Unit testing best practicesnickokiss
 
System verilog important
System verilog importantSystem verilog important
System verilog importantelumalai7
 
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 JanardhanaRavikiran J
 
Test driven development and unit testing with examples in C++
Test driven development and unit testing with examples in C++Test driven development and unit testing with examples in C++
Test driven development and unit testing with examples in C++Hong Le Van
 
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
 
05 junit
05 junit05 junit
05 junitmha4
 
Verification challenges and methodologies - SoC and ASICs
Verification challenges and methodologies - SoC and ASICsVerification challenges and methodologies - SoC and ASICs
Verification challenges and methodologies - SoC and ASICsDr. Shivananda Koteshwar
 
Refactoring_Rosenheim_2008_Workshop
Refactoring_Rosenheim_2008_WorkshopRefactoring_Rosenheim_2008_Workshop
Refactoring_Rosenheim_2008_WorkshopMax Kleiner
 
Automated Unit Testing
Automated Unit TestingAutomated Unit Testing
Automated Unit TestingMike Lively
 
Session 7 code_functional_coverage
Session 7 code_functional_coverageSession 7 code_functional_coverage
Session 7 code_functional_coverageNirav Desai
 

Was ist angesagt? (20)

Unit testing best practices
Unit testing best practicesUnit testing best practices
Unit testing best practices
 
System verilog important
System verilog importantSystem verilog important
System verilog important
 
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
 
Why Unit Testingl
Why Unit TestinglWhy Unit Testingl
Why Unit Testingl
 
Test driven development and unit testing with examples in C++
Test driven development and unit testing with examples in C++Test driven development and unit testing with examples in C++
Test driven development and unit testing with examples in C++
 
JUnit Presentation
JUnit PresentationJUnit Presentation
JUnit Presentation
 
Junit 4.0
Junit 4.0Junit 4.0
Junit 4.0
 
J Unit
J UnitJ Unit
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
 
Testing with Junit4
Testing with Junit4Testing with Junit4
Testing with Junit4
 
05 junit
05 junit05 junit
05 junit
 
JUnit 4
JUnit 4JUnit 4
JUnit 4
 
Verification challenges and methodologies - SoC and ASICs
Verification challenges and methodologies - SoC and ASICsVerification challenges and methodologies - SoC and ASICs
Verification challenges and methodologies - SoC and ASICs
 
3 j unit
3 j unit3 j unit
3 j unit
 
Unit testing with JUnit
Unit testing with JUnitUnit testing with JUnit
Unit testing with JUnit
 
Refactoring_Rosenheim_2008_Workshop
Refactoring_Rosenheim_2008_WorkshopRefactoring_Rosenheim_2008_Workshop
Refactoring_Rosenheim_2008_Workshop
 
Automated Unit Testing
Automated Unit TestingAutomated Unit Testing
Automated Unit Testing
 
Junit
JunitJunit
Junit
 
Junit
JunitJunit
Junit
 
Session 7 code_functional_coverage
Session 7 code_functional_coverageSession 7 code_functional_coverage
Session 7 code_functional_coverage
 

Andere mochten auch

Neema’s birthdayv2
Neema’s birthdayv2Neema’s birthdayv2
Neema’s birthdayv2Jerynt77
 
Neema’s birthday
Neema’s birthdayNeema’s birthday
Neema’s birthdayJerynt77
 
U.S. Sales Communications Excellence: Resources, Structure and Processes to O...
U.S. Sales Communications Excellence: Resources, Structure and Processes to O...U.S. Sales Communications Excellence: Resources, Structure and Processes to O...
U.S. Sales Communications Excellence: Resources, Structure and Processes to O...Best Practices
 
Slf sqa - using e-assessment to support cf e - 100914
Slf   sqa - using e-assessment to support cf e - 100914Slf   sqa - using e-assessment to support cf e - 100914
Slf sqa - using e-assessment to support cf e - 100914martynware
 
Change mgmt
Change mgmtChange mgmt
Change mgmtigtc
 

Andere mochten auch (8)

Neema’s birthdayv2
Neema’s birthdayv2Neema’s birthdayv2
Neema’s birthdayv2
 
2011/09/13 - Introduction
2011/09/13 - Introduction2011/09/13 - Introduction
2011/09/13 - Introduction
 
Neema’s birthday
Neema’s birthdayNeema’s birthday
Neema’s birthday
 
U.S. Sales Communications Excellence: Resources, Structure and Processes to O...
U.S. Sales Communications Excellence: Resources, Structure and Processes to O...U.S. Sales Communications Excellence: Resources, Structure and Processes to O...
U.S. Sales Communications Excellence: Resources, Structure and Processes to O...
 
Slf sqa - using e-assessment to support cf e - 100914
Slf   sqa - using e-assessment to support cf e - 100914Slf   sqa - using e-assessment to support cf e - 100914
Slf sqa - using e-assessment to support cf e - 100914
 
Change mgmt
Change mgmtChange mgmt
Change mgmt
 
Join Unicity India
Join Unicity IndiaJoin Unicity India
Join Unicity India
 
Bop animated
Bop animatedBop animated
Bop animated
 

Ähnlich wie 2011/09/21 - JUnit

JUnit- A Unit Testing Framework
JUnit- A Unit Testing FrameworkJUnit- A Unit Testing Framework
JUnit- A Unit Testing FrameworkOnkar Deshpande
 
Testing Options in Java
Testing Options in JavaTesting Options in Java
Testing Options in JavaMichael Fons
 
RPG Program for Unit Testing RPG
RPG Program for Unit Testing RPG RPG Program for Unit Testing RPG
RPG Program for Unit Testing RPG Greg.Helton
 
J unit presentation
J unit presentationJ unit presentation
J unit presentationPriya Sharma
 
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
 
PHPUnit: from zero to hero
PHPUnit: from zero to heroPHPUnit: from zero to hero
PHPUnit: from zero to heroJeremy Cook
 
utPLSQL: Unit Testing for Oracle PL/SQL
utPLSQL: Unit Testing for Oracle PL/SQLutPLSQL: Unit Testing for Oracle PL/SQL
utPLSQL: Unit Testing for Oracle PL/SQLSteven Feuerstein
 
Oh so you test? - A guide to testing on Android from Unit to Mutation
Oh so you test? - A guide to testing on Android from Unit to MutationOh so you test? - A guide to testing on Android from Unit to Mutation
Oh so you test? - A guide to testing on Android from Unit to MutationPaul Blundell
 
Testes? Mas isso não aumenta o tempo de projecto? Não quero...
Testes? Mas isso não aumenta o tempo de projecto? Não quero...Testes? Mas isso não aumenta o tempo de projecto? Não quero...
Testes? Mas isso não aumenta o tempo de projecto? Não quero...Comunidade NetPonto
 
An introduction to unit testing
An introduction to unit testingAn introduction to unit testing
An introduction to unit testingAdam Stephensen
 
Unit Testing in .NET Core 7.0 with XUnit.pptx
Unit Testing in .NET Core 7.0 with XUnit.pptxUnit Testing in .NET Core 7.0 with XUnit.pptx
Unit Testing in .NET Core 7.0 with XUnit.pptxKnoldus Inc.
 
New and improved: Coming changes to the unittest module
 	 New and improved: Coming changes to the unittest module 	 New and improved: Coming changes to the unittest module
New and improved: Coming changes to the unittest modulePyCon Italia
 
Coordinated Testing with a Test-Server
Coordinated Testing with a Test-ServerCoordinated Testing with a Test-Server
Coordinated Testing with a Test-ServerESUG
 
Unit Tests? It is Very Simple and Easy!
Unit Tests? It is Very Simple and Easy!Unit Tests? It is Very Simple and Easy!
Unit Tests? It is Very Simple and Easy!Return on Intelligence
 

Ähnlich wie 2011/09/21 - JUnit (20)

JUnit- A Unit Testing Framework
JUnit- A Unit Testing FrameworkJUnit- A Unit Testing Framework
JUnit- A Unit Testing Framework
 
Testing Options in Java
Testing Options in JavaTesting Options in Java
Testing Options in Java
 
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven Development
 
RPG Program for Unit Testing RPG
RPG Program for Unit Testing RPG RPG Program for Unit Testing RPG
RPG Program for Unit Testing RPG
 
J unit presentation
J unit presentationJ unit presentation
J unit 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)
 
PHPUnit: from zero to hero
PHPUnit: from zero to heroPHPUnit: from zero to hero
PHPUnit: from zero to hero
 
utPLSQL: Unit Testing for Oracle PL/SQL
utPLSQL: Unit Testing for Oracle PL/SQLutPLSQL: Unit Testing for Oracle PL/SQL
utPLSQL: Unit Testing for Oracle PL/SQL
 
N Unit Presentation
N Unit PresentationN Unit Presentation
N Unit Presentation
 
Junit and testNG
Junit and testNGJunit and testNG
Junit and testNG
 
Oh so you test? - A guide to testing on Android from Unit to Mutation
Oh so you test? - A guide to testing on Android from Unit to MutationOh so you test? - A guide to testing on Android from Unit to Mutation
Oh so you test? - A guide to testing on Android from Unit to Mutation
 
Testes? Mas isso não aumenta o tempo de projecto? Não quero...
Testes? Mas isso não aumenta o tempo de projecto? Não quero...Testes? Mas isso não aumenta o tempo de projecto? Não quero...
Testes? Mas isso não aumenta o tempo de projecto? Não quero...
 
Laravel Unit Testing
Laravel Unit TestingLaravel Unit Testing
Laravel Unit Testing
 
8-testing.pptx
8-testing.pptx8-testing.pptx
8-testing.pptx
 
An introduction to unit testing
An introduction to unit testingAn introduction to unit testing
An introduction to unit testing
 
Unit Testing in .NET Core 7.0 with XUnit.pptx
Unit Testing in .NET Core 7.0 with XUnit.pptxUnit Testing in .NET Core 7.0 with XUnit.pptx
Unit Testing in .NET Core 7.0 with XUnit.pptx
 
New and improved: Coming changes to the unittest module
 	 New and improved: Coming changes to the unittest module 	 New and improved: Coming changes to the unittest module
New and improved: Coming changes to the unittest module
 
L2624 labriola
L2624 labriolaL2624 labriola
L2624 labriola
 
Coordinated Testing with a Test-Server
Coordinated Testing with a Test-ServerCoordinated Testing with a Test-Server
Coordinated Testing with a Test-Server
 
Unit Tests? It is Very Simple and Easy!
Unit Tests? It is Very Simple and Easy!Unit Tests? It is Very Simple and Easy!
Unit Tests? It is Very Simple and Easy!
 

Kürzlich hochgeladen

1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Disha Kariya
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room servicediscovermytutordmt
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docxPoojaSen20
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Celine George
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphThiyagu K
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAssociation for Project Management
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajanpragatimahajan3
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 

Kürzlich hochgeladen (20)

1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room service
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docx
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajan
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 

2011/09/21 - JUnit

  • 1. Software Testing - Test Driven Development (TDD) with JUnit - Fernando Brito e Abreu DCTI / ISCTE-IUL QUASAR Research Group
  • 2. SWEBOK: the 10 Knowledge Areas  Software Requirements  Software Design  Software Construction  Software Testing  Software Maintenance  Software Configuration Management  Software Engineering Management  Software Engineering Process  Software Engineering Tools and Methods  Software Quality 27-Sep-11 Software Engineering / Fernando Brito e Abreu 2
  • 3. Working test first / TDD  Traditionally, code has been written using a test-last philosophy, i.e. design, code, then test  Testing after the fact is often boring  Write code “test first” instead:  Write a simple test (one assertion)  Write enough code to make the test pass  Repeat the process, ‘filling’ out the code 27-Sep-11 Software Engineering / Fernando Brito e Abreu 3
  • 4. Unit testing, extreme style  Tests should be an integral part of the coding process  Whenever you implement a class, also make a companion test class  Tests are executable documentation  Testsallow other programmers see how to use code  Therefore they are part of the specification 27-Sep-11 Software Engineering / Fernando Brito e Abreu 4
  • 5. Best practices  Test everything that could possibly break  This is an XP maxim and it holds  A well-written test is hard to pass  If all your tests pass the first time, you are probably not testing vigorously enough  All tests should pass before any update is made to a collective code base 27-Sep-11 Software Engineering / Fernando Brito e Abreu 5
  • 6. Best practices  When a test case fails, track down the problem by writing more tests, before going to the debugger  The more tests you have, the better  Test invalid parameters to every method, rather than just valid data  Robust software needs to recognize and handle invalid data, and the tests that pass using incorrect data are often the most informative 27-Sep-11 Software Engineering / Fernando Brito e Abreu 6
  • 7. The xUnit testing frameworks story  Kent Beck published a unit test framework for the Smalltalk language in 1999 named SmalltalkUnit (aka SUnit)  Later, Erich Gamma ported SUnit to Java, creating JUnit  Many more xUnit implementations adapted to various languages and platforms were made since  CppUnit (C++), NUnit (.Net), Dunit (Delphi), VBUnit (Visual Basic), RUnit (R), PyUnit (Pyton), HtmlUnit, XMLUnit, … 27-Sep-11 Software Engineering / Fernando Brito e Abreu 7
  • 8. JUnit for Eclipse Test class This bar is only green when all tests pass! Test error messages and tracing info appear here 27-Sep-11 selected test case for the Software Engineering / Fernando Brito e Abreu 8
  • 9. Building a test suite  A test suite is the union of the test cases for all classes in the system  A test suite should have:  One test class for each class in the system  Each test class should have at least one test method (aka test case) for each method in the class under test  To be more precise, we should have a number of test cases given by the McCabe complexity metric of the target method 27-Sep-11 Software Engineering / Fernando Brito e Abreu 9
  • 10. Test case stubs  JUnit test case stubs can be generated with Eclipse  Since only one test case stub is generated per method, you should cut and paste those stubs if McCabe complexity metric is greater than one  Method stubs look like this: @Test public final void testSomeMethod() { fail("Not yet implemented"); // TODO } 27-Sep-11 Software Engineering / Fernando Brito e Abreu 10
  • 11. Test case stubs Here we choose which stubs we want to create 27-Sep-11 Software Engineering / Fernando Brito e Abreu 11
  • 12. Test suite organization  Test code must be separated from application  Give them each their own unique directory tree with the same package naming structure  One tree using “src” as root  Another tree using “tests” as root  This lets tests live in the same package as the objects they test, while still keeping them separate during a build 27-Sep-11 Software Engineering / Fernando Brito e Abreu 12
  • 13. Test suite organization If you select a directory and do “Run As / Junit Test” all test classes contained in it (recursively) are executed. If you select a file and do “Run As / Junit Test” only the test cases in it are executed. 27-Sep-11 Software Engineering / Fernando Brito e Abreu 13
  • 14. This convention is just an Naming convention example. The important thing is using a consistent convention to facilitate maintainability.  Test classes  <test class name> ::= <class name>Test  e.g. ClientAccountTest, CurrencyTest, …  Test cases  <test case name> ::= test[<n>]<method name>.java  The <n> counter can be discarded when we have a single test (McCabe complexity = 1)  e.g. client.testgetName(), myAccount.test1deposit(), myAccount.test2deposit(), … 27-Sep-11 Software Engineering / Fernando Brito e Abreu 14
  • 15. JUnit mechanisms  Annotations  The mechanism by which JUnit determines organizes and activates your test cases  Assertions  The mechanism by which JUnit determines the success or failure of a test  An assert is a comparison between an expected value and an actual value 27-Sep-11 Software Engineering / Fernando Brito e Abreu 15
  • 16. Annotations  @BeforeClass  @AfterClass  @Before  @After  @Test  @Ignore  @Timeout 27-Sep-11 Software Engineering / Fernando Brito e Abreu 16
  • 17. @BeforeClass  This annotation allows setting up methods that will run before the full test suite contained in the class  This can be used to perform time intensive activities  Example: connect to a database There is no restriction on the names of the methods, but you should use semantically meaningful identifiers @BeforeClass public void runBeforeFullSuite() { // run once before all test cases } 27-Sep-11 Software Engineering / Fernando Brito e Abreu 17
  • 18. @AfterClass  This annotation allows setting up methods that will run after all tests contained in the class have finished  This can be used to perform clean-up activities  Example: disconnect from a database @AfterClass public void runAfterFullSuite() { // run for one time after all test cases } 27-Sep-11 Software Engineering / Fernando Brito e Abreu 18
  • 19. @Before  This annotation allows setting up all test cases, since the corresponding method will run before each test case  A @Before method can prepare the test environment  e.g. read input data, initialize the class @Before public void runBeforeEveryTest() { simpleMath = new SimpleMath(); } 27-Sep-11 Software Engineering / Fernando Brito e Abreu 19
  • 20. @After  This annotation allows tearing down test methods since it will run after every test case @After public void runAfterEveryTest() { simpleMath = null; } 27-Sep-11 Software Engineering / Fernando Brito e Abreu 20
  • 21. @Test  Mark your test cases with @Test annotations  You don’t need to prefix your test cases with “test”, although this is a good naming convention @Test public void testAddition() { assertEquals(12, simpleMath.add(7, 5)); } @Test public void testSubtraction() { assertEquals(9, simpleMath.subtract(12, 3)); } 27-Sep-11 Software Engineering / Fernando Brito e Abreu 21
  • 22. @Test  Another example: @Test public void listEquality() { List<Integer> expected = new ArrayList<Integer>(); expected.add(5); List<Integer> actual = new ArrayList<Integer>(); actual.add(5); assertEquals(expected, actual); } 27-Sep-11 Software Engineering / Fernando Brito e Abreu 22
  • 23. @Test(timeout = <delay>)  Define a timeout period in milliseconds with “timeout” parameter  The test fails when the timeout period exceeds @Test(timeout = 1000) public void infinity() { while (true) ; } 27-Sep-11 Software Engineering / Fernando Brito e Abreu 23
  • 24. @Test(expected = <exception>.class)  Tests succeeds if the method throws the exception Notice that the fail command is not executed because the exception is raised and caught by JUnit, that sees any further. 27-Sep-11 Software Engineering / Fernando Brito e Abreu 24
  • 25. @Ignore  Use this annotation for test cases you want to ignore  You can add a string parameter that defines the reason of ignorance  This may be useful if the underlying code has been changed and the test has not yet been adapted @Ignore("Not Ready to Run") @Test public void multiplication() { assertEquals(15, simpleMath.multiply(3, 5)); } 27-Sep-11 Software Engineering / Fernando Brito e Abreu 25
  • 26. Assertions  assertEquals  assertEquals for arrays  assertNull / assertNotNull  assertSame / assertNotSame  assertTrue / assertFalse  fail 27-Sep-11 Software Engineering / Fernando Brito e Abreu 26
  • 27. assertEquals  This assertion states that:  expected.equals(actual) returns true, or  both objects are null  A message is printed if supplied, when a test fails  The equality test for a double or a float should specify a maximum tolerance range (the delta), to cope with floating point errors  There are overloaded versions of this method for all Java’s primitive types assertEquals(Object expected, Object actual) assertEquals(String message, Object expected, Object actual) assertEquals(Object expected, Object actual, delta) assertEquals(String message, Engineering /expected, eObject actual, delta) 27-Sep-11 Software Object Fernando Brito Abreu 27
  • 28. assertEquals for arrays  Two arrays are equal if they have the same length and each element is equal to the corresponding element in the other array; otherwise, they’re not. public static void assertEquals(Object[] expected, Object[] actual); public static void assertEquals(String message, Object[] expected, Object[] actual); 27-Sep-11 Software Engineering / Fernando Brito e Abreu 28
  • 29. assertNull / assertNotNull  This asserts that an object reference equals null, printing a message otherwise (if supplied) assertNull(Object object), assertNull(String message, Object object)  This asserts that an object reference is not null, printing a message otherwise (if supplied) assertNotNull(Object object), assertNotNull(String message, Object) 27-Sep-11 Software Engineering / Fernando Brito e Abreu 29
  • 30. assertSame / assertNotSame  Asserts that the two objects are the same, printing a message otherwise (if supplied)  Thisis a stricter condition than simple equality, as it compares the object identities using expected == actual assertSame(Object expected, Object actual) assertSame(String message, Object expected, Object actual)  Asserts that the two objects are not the same, printing a message otherwise (if supplied) assertNotSame(Object expected, Object actual) assertNotSame(String message, Object expected, Object actual) 27-Sep-11 Software Engineering / Fernando Brito e Abreu 30
  • 31. assertTrue / assertFalse  Asserts that the condition is true, printing a message otherwise (if supplied) assertTrue(boolean condition) assertTrue(String message, boolean condition)  Asserts that the condition is false, printing a message otherwise (if supplied) assertFalse(boolean condition) assertFalse(String message, boolean condition) 27-Sep-11 Software Engineering / Fernando Brito e Abreu 31
  • 32. fail  This forces a failure. This is useful to close off paths through the code that should not be reached fail() fail(String message) 27-Sep-11 Software Engineering / Fernando Brito e Abreu 32
  • 33. More Reading  http://www.junit.org/index.htm  http://open.ncsu.edu/se/tutorials/junit/  http://www.cs.umanitoba.ca/~eclipse/10-JUnit.pdf  http://supportweb.cs.bham.ac.uk/documentation/tutorial s/docsystem/build/tutorials/junit/junit.pdf  http://junit.sourceforge.net/javadoc/junit/framework/ 27-Sep-11 Software Engineering / Fernando Brito e Abreu 33