SlideShare une entreprise Scribd logo
1  sur  25
Planning and Managing Software Projects 2011-12



Unit testing

Emanuele Della Valle, Lecturer: Daniele Dell’Aglio
http://emanueledellavalle.org
Outline

●    Unit testing
●    JUnit
      –    Test cases
      –    Setup and Tear Down
      –    Test suites




 Planning and Managing Software Projects – Emanuele Della Valle
Unit testing
●    The primary goal of unit testing is to take
     the smallest piece of testable software in
     the application, isolate it from the
     remainder of the code, and determine
     whether it behaves exactly as you
     expect [msdn]
●    In computer programming, unit testing is a
     method by which individual units of source
     code, sets of one or more computer
     program modules together with associated
     control data, usage procedures, and
     operating procedures, are tested to
     determine if they are fit for use.
     [wikipedia]


 Planning and Managing Software Projects – Emanuele Della Valle
Unit testing
●    The goal is to write tests for the two
     situations
      –    If the tested software component works
           properly when its inputs are valid and the
           pre-conditions are verified (Positive testing)
      –    If the tested software component behaves in
           the proper way in the other case (Negative
           testing)
●    Code and test, code and test!
      –    Writing test after that all the code is written
           is complicated and time consuming
      –    Tests help in checking if the development
           introduces errors
 Planning and Managing Software Projects – Emanuele Della Valle
Unit testing – Key concepts

●    Test case: method that can be executed
     to check if the behaviour of one or more
     objects is valid
●    Test fixture: the context of the test –
     usually it is the set of objects on which
     the tests will run against
●    Test suite: collection of test cases and
     related test fixtures that can be executed




 Planning and Managing Software Projects – Emanuele Della Valle
Why Unit Testing?

●   How to verify if the code works?
●   Debug expressions
        Easy to do                                                 Only one debug expression at a
        Can be done at runtime                                      time
                                                                    Human effort to verify the result


●   Test expressions
        Easy to write                                              Scroll Blindness
        Can be inserted in every part of the                       Execution of the whole code
         code                                                       Human effort to verify the result


●   Unit testing
        Focus on one component                                     Require a lot of time to be written
        Repeatable
        Automatic verification of the results


Planning and Managing Software Projects – Emanuele Della Valle
JUnit

●    JUnit is a unit testing framework for Java
●    http://junit.org
●    Today we focus on JUnit 4.x
      –    Same concepts of previous versions
      –    Based on Java annotations (instead of
           inheritance)




 Planning and Managing Software Projects – Emanuele Della Valle
Example (example1 - TreeNode.java)
public class TreeNode{
   private String content;
   private TreeNode parent;
   private List<TreeNode> children;
   public TreeNode(){
     super();
     children=new ArrayList<TreeNode>();
   }
   public void addChild(TreeNode node){
     children.add(node);
   }
   public List<TreeNode> getChildren(){
     return children;
   }
}
    Planning and Managing Software Projects – Emanuele Della Valle
JUnit – Test cases

●    Test cases are Java methods such as
        @Test public void testCaseName(){...}
●    @Test is the JUnit annotation to indicate
     that the method is a test
●    The method doesn't have parameter
●    The method returns void




 Planning and Managing Software Projects – Emanuele Della Valle
JUnit – Test cases

●    The body of the test method contains the
     code to verify the satisfaction of the
     conditions
●    It is done through Assertions
      –    assertNull(Object o)
      –    assertNotNull(Object x)
      –    assertEquals(Object a, Object b)
      –    ...



(the full list is available at:
   http://junit.sourceforge.net/javadoc/org/junit/Assert.html)
 Planning and Managing Software Projects – Emanuele Della Valle
Example (example2 - TreeNodeTest.java)
public class TreeNodeTest{
   @Test
   public void shouldAddChildInTail(){
     TreeNode root = new TreeNode();
     TreeNode firstChild = new TreeNode();
     firstChild.setContent("content1");
     root.addChild(firstChild);
     TreeNode secondChild = new TreeNode();
     secondChild.setContent("content2");
     root.addChildren(secondChild);
     int lastElement=root.getChildren().size()-1;
     TreeNode lastChild =
           root.getChildren().get(lastElement);
     assertEquals(secondChild, lastChild);
   }
}
    Planning and Managing Software Projects – Emanuele Della Valle
Example (example2 - TreeNodeTest.java)
public class TreeNodeTest{
   @Test public void shouldAddChildInTail(){...}

         @Test
         public void childShouldHaveTheParent(){
           TreeNode root = new TreeNode();
           TreeNode child = new TreeNode();
           root.addChild(child);
           TreeNode parent =
                 root.getChildren().get(0).getParent();
           assertEquals(root, parent);
         }
}



    Planning and Managing Software Projects – Emanuele Della Valle
Example (example2 - TreeNode.java)
Let’s fix the method code...
public class TreeNode{
   ...
   public void addChild(TreeNode node){
     node.setParent(this);
     childrens.add(node);
   }
   ...
}

Now the all the tests run and are successful!




    Planning and Managing Software Projects – Emanuele Della Valle
JUnit – Test cases

●    For Negative testings it is possible to set
     an expected exception as parameter of
     the @Test annotation
    @Test(expected=ExpectedException.class)...



●    It is possible to exclude the execution of
     a test case using the @Ignore annotation
          @Ignore(“reason”)@Test public void ...




 Planning and Managing Software Projects – Emanuele Della Valle
Example (example3 - TreeNodeNegTest.java)
public class TreeNodeNegTest{
   @Test(expected=NotOrphanException.class)
   public void nodeCannotHaveAnotherParent(){
     TreeNode root = new TreeNode();
     TreeNode root2 = new TreeNode();
     TreeNode child = new TreeNode();
     root.addChild(child);
     root2.addChild(child);
   }
}




    Planning and Managing Software Projects – Emanuele Della Valle
Example (example3 - TreeNode.java)
public class TreeNode{
   ...
   public void addChild(TreeNode node){
     if(node.getParent()!=null)
           throw new NotOrphanException(node);
     node.setParent(this);
     childrens.add(node);
   }
   ...
}

Now the the test returns an exception!




    Planning and Managing Software Projects – Emanuele Della Valle
JUnit – Setup

●    The setup is done through @Before and
     @BeforeClass annotations
      –    It allows to define the fixture
●    Methods annotated with @Before are
     executed before the execution of each
     test case
●    Methods annotated with @BeforeClass
     are the first to be executed




 Planning and Managing Software Projects – Emanuele Della Valle
JUnit – Tear Down

●   The tear down is done through @After
    and @AfterClass annotations
     –    Used to destroy the fixture and reset the
          status before the test execution
●   Methods annotated with @After are
    executed after the execution of each test
    case
●   Methods annotated with @AfterClass
    are executed after the execution of all
    the test methods and all the @After
    annotated methods
Planning and Managing Software Projects – Emanuele Della Valle
Example (example4 - TreeNodeTest.java)
public class TreeNodeTest{
   private TreeNode root;
   private TreeNode child;
   @Before
   public void setup(){
     root=new TreeNode();
     child=new TreeNode();
     root.addChild(child);
   }
   ...
}



Now we have to fix the code of the tests...


    Planning and Managing Software Projects – Emanuele Della Valle
Example (TreeNodeTest.java)
public class TreeNodeTest{
   ...
   @Test public void shouldAddChildInTail(){
     TreeNode secondChild = new TreeNode();
     secondChild.setContent("content2");
     root.addChild(secondChild);
     TreeNode lastChild =
           root.getChildren().getLast();
     assertEquals(secondChild, lastChild);
   }
   @Test public void childShouldHaveTheParent(){
     TreeNode parent =
           root.getChildren().get(0).getParent();
     assertEquals(root, parent);
   }
}
    Planning and Managing Software Projects – Emanuele Della Valle
Test suite

●    In order to execute the test cases a test
     suite class is required
●    @RunWith and @SuiteClasses are the
     annotations that define a test suite:
      –    @RunWith indicates the test runner (a class
           implementing org.junit.runner.Runner)
      –    @SuiteClasses defines the list of the classes
           containing the test cases of the test suite
●    It is also possible to use the Java program:
               org.junit.runner.JUnitCore.runClasses(
                                         TestClass1, TestClass2, ...);


 Planning and Managing Software Projects – Emanuele Della Valle
Example (example5 - TreeNodeTestSuite.java)
@RunWith(Suite.class)
@SuiteClasses({TreeNodeTest.class,
     TreeNodeNegTest.class})
public class TreeNodeTestSuite{
}




    Planning and Managing Software Projects – Emanuele Della Valle
Test Suite lifecycle



                                           @BeforeClass
                                            methods

                                                                  • @Before methods
                                            For each test:        • @Test method
                                                                  • @After methods

                                             @AfterClass
                                              methods


 Planning and Managing Software Projects – Emanuele Della Valle
JUnit – some best practices

●    Write the tests before the tested code
      –    Test-driven Development
●    Put the test cases in the same package
     of the tested classes but in a different
     source folder
      –    It enables the test of the protected methods
●    Execute all the tests every time you
     change something!




 Planning and Managing Software Projects – Emanuele Della Valle
References
 JUnit Test Infected: Programmers Love Writing Tests
  http://junit.sourceforge.net/doc/testinfected/testing.ht
  m
 JUnit Cookbook
  http://junit.sourceforge.net/doc/cookbook/cookbook.ht
  m
 JUnit and EasyMock (Dzone RefCard)
  http://refcardz.dzone.com/refcardz/junit-and-
  easymock
 JUnit Kung Fu: Getting More Out of Your Unit Tests
  http://weblogs.java.net/blog/johnsmart/archive/2010/
  09/30/junit-kung-fu-getting-more-out-your-unit-tests




 Planning and Managing Software Projects – Emanuele Della Valle

Contenu connexe

Tendances

05 junit
05 junit05 junit
05 junitmha4
 
Gui path oriented test generation algorithms paper
Gui path oriented test generation algorithms paperGui path oriented test generation algorithms paper
Gui path oriented test generation algorithms paperIzzat Alsmadi
 
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven DevelopmentDhaval Dalal
 
Must.kill.mutants. TopConf Tallinn 2016
Must.kill.mutants. TopConf Tallinn 2016Must.kill.mutants. TopConf Tallinn 2016
Must.kill.mutants. TopConf Tallinn 2016Gerald Muecke
 
Test-Driven Development
Test-Driven DevelopmentTest-Driven Development
Test-Driven DevelopmentJohn Blum
 
An Introduction to Test Driven Development
An Introduction to Test Driven Development An Introduction to Test Driven Development
An Introduction to Test Driven Development CodeOps Technologies LLP
 
Unit Testing & TDD Training for Mobile Apps
Unit Testing & TDD Training for Mobile AppsUnit Testing & TDD Training for Mobile Apps
Unit Testing & TDD Training for Mobile AppsMarcelo Busico
 
Automation testing by Durgasoft in Hyderabad
Automation testing by Durgasoft in HyderabadAutomation testing by Durgasoft in Hyderabad
Automation testing by Durgasoft in HyderabadDurga Prasad
 
Introduction to TDD with FlexUnit
Introduction to TDD with FlexUnitIntroduction to TDD with FlexUnit
Introduction to TDD with FlexUnitAnupom Syam
 
MTLM Visual Studio 2010 ALM workshop - day1
MTLM Visual Studio 2010 ALM workshop  - day1MTLM Visual Studio 2010 ALM workshop  - day1
MTLM Visual Studio 2010 ALM workshop - day1Clemens Reijnen
 
A Study: The Analysis of Test Driven Development And Design Driven Test
A Study: The Analysis of Test Driven Development And Design Driven TestA Study: The Analysis of Test Driven Development And Design Driven Test
A Study: The Analysis of Test Driven Development And Design Driven TestEditor IJMTER
 
Towards Malware Decompilation and Reassembly
Towards Malware Decompilation and ReassemblyTowards Malware Decompilation and Reassembly
Towards Malware Decompilation and ReassemblyMarcus Botacin
 
Open Source tools in Continuous Integration environment (case study for agil...
Open Source tools in Continuous Integration environment  (case study for agil...Open Source tools in Continuous Integration environment  (case study for agil...
Open Source tools in Continuous Integration environment (case study for agil...suwalki24.pl
 
Design for Testability
Design for Testability Design for Testability
Design for Testability Pawel Kalbrun
 
Unit testing with Junit
Unit testing with JunitUnit testing with Junit
Unit testing with JunitValerio Maggio
 

Tendances (20)

05 junit
05 junit05 junit
05 junit
 
Gui path oriented test generation algorithms paper
Gui path oriented test generation algorithms paperGui path oriented test generation algorithms paper
Gui path oriented test generation algorithms paper
 
Unit testing with JUnit
Unit testing with JUnitUnit testing with JUnit
Unit testing with JUnit
 
Ch 6 randomization
Ch 6 randomizationCh 6 randomization
Ch 6 randomization
 
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven Development
 
Testing 101
Testing 101Testing 101
Testing 101
 
Must.kill.mutants. TopConf Tallinn 2016
Must.kill.mutants. TopConf Tallinn 2016Must.kill.mutants. TopConf Tallinn 2016
Must.kill.mutants. TopConf Tallinn 2016
 
Test-Driven Development
Test-Driven DevelopmentTest-Driven Development
Test-Driven Development
 
Junit tutorial
Junit tutorialJunit tutorial
Junit tutorial
 
An Introduction to Test Driven Development
An Introduction to Test Driven Development An Introduction to Test Driven Development
An Introduction to Test Driven Development
 
Unit Testing & TDD Training for Mobile Apps
Unit Testing & TDD Training for Mobile AppsUnit Testing & TDD Training for Mobile Apps
Unit Testing & TDD Training for Mobile Apps
 
Automation testing by Durgasoft in Hyderabad
Automation testing by Durgasoft in HyderabadAutomation testing by Durgasoft in Hyderabad
Automation testing by Durgasoft in Hyderabad
 
Introduction to TDD with FlexUnit
Introduction to TDD with FlexUnitIntroduction to TDD with FlexUnit
Introduction to TDD with FlexUnit
 
MTLM Visual Studio 2010 ALM workshop - day1
MTLM Visual Studio 2010 ALM workshop  - day1MTLM Visual Studio 2010 ALM workshop  - day1
MTLM Visual Studio 2010 ALM workshop - day1
 
A Study: The Analysis of Test Driven Development And Design Driven Test
A Study: The Analysis of Test Driven Development And Design Driven TestA Study: The Analysis of Test Driven Development And Design Driven Test
A Study: The Analysis of Test Driven Development And Design Driven Test
 
Towards Malware Decompilation and Reassembly
Towards Malware Decompilation and ReassemblyTowards Malware Decompilation and Reassembly
Towards Malware Decompilation and Reassembly
 
Open Source tools in Continuous Integration environment (case study for agil...
Open Source tools in Continuous Integration environment  (case study for agil...Open Source tools in Continuous Integration environment  (case study for agil...
Open Source tools in Continuous Integration environment (case study for agil...
 
Unit Testing
Unit TestingUnit Testing
Unit Testing
 
Design for Testability
Design for Testability Design for Testability
Design for Testability
 
Unit testing with Junit
Unit testing with JunitUnit testing with Junit
Unit testing with Junit
 

En vedette

Rapid final presentation the illuminators
Rapid final presentation the illuminatorsRapid final presentation the illuminators
Rapid final presentation the illuminatorsEd Tackett
 
RDF Stream Processing Models (SR4LD2013)
RDF Stream Processing Models (SR4LD2013)RDF Stream Processing Models (SR4LD2013)
RDF Stream Processing Models (SR4LD2013)Daniele Dell'Aglio
 
Mediene i krig og fred 1940 1960
Mediene i krig og fred 1940 1960Mediene i krig og fred 1940 1960
Mediene i krig og fred 1940 1960Lene Gaustad
 
P&MSP2012 - Version Control Systems
P&MSP2012 - Version Control SystemsP&MSP2012 - Version Control Systems
P&MSP2012 - Version Control SystemsDaniele Dell'Aglio
 
RDF Stream Processing Models (RSP2014)
RDF Stream Processing Models (RSP2014)RDF Stream Processing Models (RSP2014)
RDF Stream Processing Models (RSP2014)Daniele Dell'Aglio
 

En vedette (6)

Rapid final presentation the illuminators
Rapid final presentation the illuminatorsRapid final presentation the illuminators
Rapid final presentation the illuminators
 
RDF Stream Processing Models (SR4LD2013)
RDF Stream Processing Models (SR4LD2013)RDF Stream Processing Models (SR4LD2013)
RDF Stream Processing Models (SR4LD2013)
 
Mediene i krig og fred 1940 1960
Mediene i krig og fred 1940 1960Mediene i krig og fred 1940 1960
Mediene i krig og fred 1940 1960
 
P&MSP2012 - Version Control Systems
P&MSP2012 - Version Control SystemsP&MSP2012 - Version Control Systems
P&MSP2012 - Version Control Systems
 
RDF Stream Processing Models (RSP2014)
RDF Stream Processing Models (RSP2014)RDF Stream Processing Models (RSP2014)
RDF Stream Processing Models (RSP2014)
 
Lampiran unit root test
Lampiran unit root testLampiran unit root test
Lampiran unit root test
 

Similaire à P&MSP2012 - Unit Testing

Testing And Drupal
Testing And DrupalTesting And Drupal
Testing And DrupalPeter Arato
 
Test Driven Development with Sql Server
Test Driven Development with Sql ServerTest Driven Development with Sql Server
Test Driven Development with Sql ServerDavid P. Moore
 
Test driven development in .Net - 2010 + Eclipse
Test driven development in .Net - 2010 + EclipseTest driven development in .Net - 2010 + Eclipse
Test driven development in .Net - 2010 + EclipseUTC Fire & Security
 
Break through e2e-testing
Break through e2e-testingBreak through e2e-testing
Break through e2e-testingtameemahmed5
 
Behaviour Driven Development and Thinking About Testing
Behaviour Driven Development and Thinking About TestingBehaviour Driven Development and Thinking About Testing
Behaviour Driven Development and Thinking About Testingdn
 
Unit testing & TDD concepts with best practice guidelines.
Unit testing & TDD concepts with best practice guidelines.Unit testing & TDD concepts with best practice guidelines.
Unit testing & TDD concepts with best practice guidelines.Mohamed Taman
 
Drupalcamp Simpletest
Drupalcamp SimpletestDrupalcamp Simpletest
Drupalcamp Simpletestlyricnz
 
Testing In Drupal
Testing In DrupalTesting In Drupal
Testing In DrupalRyan Cross
 
JUnit- A Unit Testing Framework
JUnit- A Unit Testing FrameworkJUnit- A Unit Testing Framework
JUnit- A Unit Testing FrameworkOnkar Deshpande
 
ch11lect1.ppt
ch11lect1.pptch11lect1.ppt
ch11lect1.pptImXaib
 
ch11lect1.pptghjgjhjkkljkkkjkjkjljkjhytytgh
ch11lect1.pptghjgjhjkkljkkkjkjkjljkjhytytghch11lect1.pptghjgjhjkkljkkkjkjkjljkjhytytgh
ch11lect1.pptghjgjhjkkljkkkjkjkjljkjhytytghssuser2d043c
 
Unit Testing in Flutter - From Workflow Essentials to Complex Scenarios
Unit Testing in Flutter - From Workflow Essentials to Complex ScenariosUnit Testing in Flutter - From Workflow Essentials to Complex Scenarios
Unit Testing in Flutter - From Workflow Essentials to Complex ScenariosFlutter Agency
 
Unit testing php-unit - phing - selenium_v2
Unit testing   php-unit - phing - selenium_v2Unit testing   php-unit - phing - selenium_v2
Unit testing php-unit - phing - selenium_v2Tricode (part of Dept)
 

Similaire à P&MSP2012 - Unit Testing (20)

TDD Workshop UTN 2012
TDD Workshop UTN 2012TDD Workshop UTN 2012
TDD Workshop UTN 2012
 
Testing And Drupal
Testing And DrupalTesting And Drupal
Testing And Drupal
 
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven Development
 
Test Driven Development with Sql Server
Test Driven Development with Sql ServerTest Driven Development with Sql Server
Test Driven Development with Sql Server
 
Test driven development in .Net - 2010 + Eclipse
Test driven development in .Net - 2010 + EclipseTest driven development in .Net - 2010 + Eclipse
Test driven development in .Net - 2010 + Eclipse
 
Break through e2e-testing
Break through e2e-testingBreak through e2e-testing
Break through e2e-testing
 
Ase02.ppt
Ase02.pptAse02.ppt
Ase02.ppt
 
Behaviour Driven Development and Thinking About Testing
Behaviour Driven Development and Thinking About TestingBehaviour Driven Development and Thinking About Testing
Behaviour Driven Development and Thinking About Testing
 
Unit testing & TDD concepts with best practice guidelines.
Unit testing & TDD concepts with best practice guidelines.Unit testing & TDD concepts with best practice guidelines.
Unit testing & TDD concepts with best practice guidelines.
 
Drupalcamp Simpletest
Drupalcamp SimpletestDrupalcamp Simpletest
Drupalcamp Simpletest
 
Testing In Drupal
Testing In DrupalTesting In Drupal
Testing In Drupal
 
Junit and testNG
Junit and testNGJunit and testNG
Junit and testNG
 
JUnit- A Unit Testing Framework
JUnit- A Unit Testing FrameworkJUnit- A Unit Testing Framework
JUnit- A Unit Testing Framework
 
N Unit Presentation
N Unit PresentationN Unit Presentation
N Unit Presentation
 
ch11lect1.ppt
ch11lect1.pptch11lect1.ppt
ch11lect1.ppt
 
ch11lect1.pptghjgjhjkkljkkkjkjkjljkjhytytgh
ch11lect1.pptghjgjhjkkljkkkjkjkjljkjhytytghch11lect1.pptghjgjhjkkljkkkjkjkjljkjhytytgh
ch11lect1.pptghjgjhjkkljkkkjkjkjljkjhytytgh
 
ch11lect1.ppt
ch11lect1.pptch11lect1.ppt
ch11lect1.ppt
 
Unit Testing in Flutter - From Workflow Essentials to Complex Scenarios
Unit Testing in Flutter - From Workflow Essentials to Complex ScenariosUnit Testing in Flutter - From Workflow Essentials to Complex Scenarios
Unit Testing in Flutter - From Workflow Essentials to Complex Scenarios
 
Unit testing php-unit - phing - selenium_v2
Unit testing   php-unit - phing - selenium_v2Unit testing   php-unit - phing - selenium_v2
Unit testing php-unit - phing - selenium_v2
 
Test ng for testers
Test ng for testersTest ng for testers
Test ng for testers
 

Plus de Daniele Dell'Aglio

Distributed stream consistency checking
Distributed stream consistency checkingDistributed stream consistency checking
Distributed stream consistency checkingDaniele Dell'Aglio
 
Triplewave: a step towards RDF Stream Processing on the Web
Triplewave: a step towards RDF Stream Processing on the WebTriplewave: a step towards RDF Stream Processing on the Web
Triplewave: a step towards RDF Stream Processing on the WebDaniele Dell'Aglio
 
On unifying query languages for RDF streams
On unifying query languages for RDF streamsOn unifying query languages for RDF streams
On unifying query languages for RDF streamsDaniele Dell'Aglio
 
RSEP-QL: A Query Model to Capture Event Pattern Matching in RDF Stream Proces...
RSEP-QL: A Query Model to Capture Event Pattern Matching in RDF Stream Proces...RSEP-QL: A Query Model to Capture Event Pattern Matching in RDF Stream Proces...
RSEP-QL: A Query Model to Capture Event Pattern Matching in RDF Stream Proces...Daniele Dell'Aglio
 
Summary of the Stream Reasoning workshop at ISWC 2016
Summary of the Stream Reasoning workshop at ISWC 2016Summary of the Stream Reasoning workshop at ISWC 2016
Summary of the Stream Reasoning workshop at ISWC 2016Daniele Dell'Aglio
 
On Unified Stream Reasoning - The RDF Stream Processing realm
On Unified Stream Reasoning - The RDF Stream Processing realmOn Unified Stream Reasoning - The RDF Stream Processing realm
On Unified Stream Reasoning - The RDF Stream Processing realmDaniele Dell'Aglio
 
Querying the Web of Data with XSPARQL 1.1
Querying the Web of Data with XSPARQL 1.1Querying the Web of Data with XSPARQL 1.1
Querying the Web of Data with XSPARQL 1.1Daniele Dell'Aglio
 
Augmented Participation to Live Events through Social Network Content Enrichm...
Augmented Participation to Live Events through Social Network Content Enrichm...Augmented Participation to Live Events through Social Network Content Enrichm...
Augmented Participation to Live Events through Social Network Content Enrichm...Daniele Dell'Aglio
 
An experience on empirical research about rdf stream
An experience on empirical research about rdf streamAn experience on empirical research about rdf stream
An experience on empirical research about rdf streamDaniele Dell'Aglio
 
A Survey of Temporal Extensions of Description Logics
A Survey of Temporal Extensions of Description LogicsA Survey of Temporal Extensions of Description Logics
A Survey of Temporal Extensions of Description LogicsDaniele Dell'Aglio
 
IMaRS - Incremental Materialization for RDF Streams (SR4LD2013)
IMaRS - Incremental Materialization for RDF Streams (SR4LD2013)IMaRS - Incremental Materialization for RDF Streams (SR4LD2013)
IMaRS - Incremental Materialization for RDF Streams (SR4LD2013)Daniele Dell'Aglio
 
Ontology based top-k query answering over massive, heterogeneous, and dynamic...
Ontology based top-k query answering over massive, heterogeneous, and dynamic...Ontology based top-k query answering over massive, heterogeneous, and dynamic...
Ontology based top-k query answering over massive, heterogeneous, and dynamic...Daniele Dell'Aglio
 
On correctness in RDF stream processor benchmarking
On correctness in RDF stream processor benchmarkingOn correctness in RDF stream processor benchmarking
On correctness in RDF stream processor benchmarkingDaniele Dell'Aglio
 
An Ontological Formulation and an OPM profile for Causality in Planning Appli...
An Ontological Formulation and an OPM profile for Causality in Planning Appli...An Ontological Formulation and an OPM profile for Causality in Planning Appli...
An Ontological Formulation and an OPM profile for Causality in Planning Appli...Daniele Dell'Aglio
 
P&MSP2012 - Logging Frameworks
P&MSP2012 - Logging FrameworksP&MSP2012 - Logging Frameworks
P&MSP2012 - Logging FrameworksDaniele Dell'Aglio
 

Plus de Daniele Dell'Aglio (19)

Distributed stream consistency checking
Distributed stream consistency checkingDistributed stream consistency checking
Distributed stream consistency checking
 
On web stream processing
On web stream processingOn web stream processing
On web stream processing
 
On a web of data streams
On a web of data streamsOn a web of data streams
On a web of data streams
 
Triplewave: a step towards RDF Stream Processing on the Web
Triplewave: a step towards RDF Stream Processing on the WebTriplewave: a step towards RDF Stream Processing on the Web
Triplewave: a step towards RDF Stream Processing on the Web
 
On unifying query languages for RDF streams
On unifying query languages for RDF streamsOn unifying query languages for RDF streams
On unifying query languages for RDF streams
 
RSEP-QL: A Query Model to Capture Event Pattern Matching in RDF Stream Proces...
RSEP-QL: A Query Model to Capture Event Pattern Matching in RDF Stream Proces...RSEP-QL: A Query Model to Capture Event Pattern Matching in RDF Stream Proces...
RSEP-QL: A Query Model to Capture Event Pattern Matching in RDF Stream Proces...
 
Summary of the Stream Reasoning workshop at ISWC 2016
Summary of the Stream Reasoning workshop at ISWC 2016Summary of the Stream Reasoning workshop at ISWC 2016
Summary of the Stream Reasoning workshop at ISWC 2016
 
On Unified Stream Reasoning
On Unified Stream ReasoningOn Unified Stream Reasoning
On Unified Stream Reasoning
 
On Unified Stream Reasoning - The RDF Stream Processing realm
On Unified Stream Reasoning - The RDF Stream Processing realmOn Unified Stream Reasoning - The RDF Stream Processing realm
On Unified Stream Reasoning - The RDF Stream Processing realm
 
Querying the Web of Data with XSPARQL 1.1
Querying the Web of Data with XSPARQL 1.1Querying the Web of Data with XSPARQL 1.1
Querying the Web of Data with XSPARQL 1.1
 
Augmented Participation to Live Events through Social Network Content Enrichm...
Augmented Participation to Live Events through Social Network Content Enrichm...Augmented Participation to Live Events through Social Network Content Enrichm...
Augmented Participation to Live Events through Social Network Content Enrichm...
 
An experience on empirical research about rdf stream
An experience on empirical research about rdf streamAn experience on empirical research about rdf stream
An experience on empirical research about rdf stream
 
A Survey of Temporal Extensions of Description Logics
A Survey of Temporal Extensions of Description LogicsA Survey of Temporal Extensions of Description Logics
A Survey of Temporal Extensions of Description Logics
 
IMaRS - Incremental Materialization for RDF Streams (SR4LD2013)
IMaRS - Incremental Materialization for RDF Streams (SR4LD2013)IMaRS - Incremental Materialization for RDF Streams (SR4LD2013)
IMaRS - Incremental Materialization for RDF Streams (SR4LD2013)
 
Ontology based top-k query answering over massive, heterogeneous, and dynamic...
Ontology based top-k query answering over massive, heterogeneous, and dynamic...Ontology based top-k query answering over massive, heterogeneous, and dynamic...
Ontology based top-k query answering over massive, heterogeneous, and dynamic...
 
On correctness in RDF stream processor benchmarking
On correctness in RDF stream processor benchmarkingOn correctness in RDF stream processor benchmarking
On correctness in RDF stream processor benchmarking
 
An Ontological Formulation and an OPM profile for Causality in Planning Appli...
An Ontological Formulation and an OPM profile for Causality in Planning Appli...An Ontological Formulation and an OPM profile for Causality in Planning Appli...
An Ontological Formulation and an OPM profile for Causality in Planning Appli...
 
P&MSP2012 - Maven
P&MSP2012 - MavenP&MSP2012 - Maven
P&MSP2012 - Maven
 
P&MSP2012 - Logging Frameworks
P&MSP2012 - Logging FrameworksP&MSP2012 - Logging Frameworks
P&MSP2012 - Logging Frameworks
 

Dernier

Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfPrecisely
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionDilum Bandara
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostZilliz
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfRankYa
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 

Dernier (20)

Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdf
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 

P&MSP2012 - Unit Testing

  • 1. Planning and Managing Software Projects 2011-12 Unit testing Emanuele Della Valle, Lecturer: Daniele Dell’Aglio http://emanueledellavalle.org
  • 2. Outline ● Unit testing ● JUnit – Test cases – Setup and Tear Down – Test suites Planning and Managing Software Projects – Emanuele Della Valle
  • 3. Unit testing ● The primary goal of unit testing is to take the smallest piece of testable software in the application, isolate it from the remainder of the code, and determine whether it behaves exactly as you expect [msdn] ● In computer programming, unit testing is a method by which individual units of source code, sets of one or more computer program modules together with associated control data, usage procedures, and operating procedures, are tested to determine if they are fit for use. [wikipedia] Planning and Managing Software Projects – Emanuele Della Valle
  • 4. Unit testing ● The goal is to write tests for the two situations – If the tested software component works properly when its inputs are valid and the pre-conditions are verified (Positive testing) – If the tested software component behaves in the proper way in the other case (Negative testing) ● Code and test, code and test! – Writing test after that all the code is written is complicated and time consuming – Tests help in checking if the development introduces errors Planning and Managing Software Projects – Emanuele Della Valle
  • 5. Unit testing – Key concepts ● Test case: method that can be executed to check if the behaviour of one or more objects is valid ● Test fixture: the context of the test – usually it is the set of objects on which the tests will run against ● Test suite: collection of test cases and related test fixtures that can be executed Planning and Managing Software Projects – Emanuele Della Valle
  • 6. Why Unit Testing? ● How to verify if the code works? ● Debug expressions  Easy to do  Only one debug expression at a  Can be done at runtime time  Human effort to verify the result ● Test expressions  Easy to write  Scroll Blindness  Can be inserted in every part of the  Execution of the whole code code  Human effort to verify the result ● Unit testing  Focus on one component  Require a lot of time to be written  Repeatable  Automatic verification of the results Planning and Managing Software Projects – Emanuele Della Valle
  • 7. JUnit ● JUnit is a unit testing framework for Java ● http://junit.org ● Today we focus on JUnit 4.x – Same concepts of previous versions – Based on Java annotations (instead of inheritance) Planning and Managing Software Projects – Emanuele Della Valle
  • 8. Example (example1 - TreeNode.java) public class TreeNode{ private String content; private TreeNode parent; private List<TreeNode> children; public TreeNode(){ super(); children=new ArrayList<TreeNode>(); } public void addChild(TreeNode node){ children.add(node); } public List<TreeNode> getChildren(){ return children; } } Planning and Managing Software Projects – Emanuele Della Valle
  • 9. JUnit – Test cases ● Test cases are Java methods such as @Test public void testCaseName(){...} ● @Test is the JUnit annotation to indicate that the method is a test ● The method doesn't have parameter ● The method returns void Planning and Managing Software Projects – Emanuele Della Valle
  • 10. JUnit – Test cases ● The body of the test method contains the code to verify the satisfaction of the conditions ● It is done through Assertions – assertNull(Object o) – assertNotNull(Object x) – assertEquals(Object a, Object b) – ... (the full list is available at: http://junit.sourceforge.net/javadoc/org/junit/Assert.html) Planning and Managing Software Projects – Emanuele Della Valle
  • 11. Example (example2 - TreeNodeTest.java) public class TreeNodeTest{ @Test public void shouldAddChildInTail(){ TreeNode root = new TreeNode(); TreeNode firstChild = new TreeNode(); firstChild.setContent("content1"); root.addChild(firstChild); TreeNode secondChild = new TreeNode(); secondChild.setContent("content2"); root.addChildren(secondChild); int lastElement=root.getChildren().size()-1; TreeNode lastChild = root.getChildren().get(lastElement); assertEquals(secondChild, lastChild); } } Planning and Managing Software Projects – Emanuele Della Valle
  • 12. Example (example2 - TreeNodeTest.java) public class TreeNodeTest{ @Test public void shouldAddChildInTail(){...} @Test public void childShouldHaveTheParent(){ TreeNode root = new TreeNode(); TreeNode child = new TreeNode(); root.addChild(child); TreeNode parent = root.getChildren().get(0).getParent(); assertEquals(root, parent); } } Planning and Managing Software Projects – Emanuele Della Valle
  • 13. Example (example2 - TreeNode.java) Let’s fix the method code... public class TreeNode{ ... public void addChild(TreeNode node){ node.setParent(this); childrens.add(node); } ... } Now the all the tests run and are successful! Planning and Managing Software Projects – Emanuele Della Valle
  • 14. JUnit – Test cases ● For Negative testings it is possible to set an expected exception as parameter of the @Test annotation @Test(expected=ExpectedException.class)... ● It is possible to exclude the execution of a test case using the @Ignore annotation @Ignore(“reason”)@Test public void ... Planning and Managing Software Projects – Emanuele Della Valle
  • 15. Example (example3 - TreeNodeNegTest.java) public class TreeNodeNegTest{ @Test(expected=NotOrphanException.class) public void nodeCannotHaveAnotherParent(){ TreeNode root = new TreeNode(); TreeNode root2 = new TreeNode(); TreeNode child = new TreeNode(); root.addChild(child); root2.addChild(child); } } Planning and Managing Software Projects – Emanuele Della Valle
  • 16. Example (example3 - TreeNode.java) public class TreeNode{ ... public void addChild(TreeNode node){ if(node.getParent()!=null) throw new NotOrphanException(node); node.setParent(this); childrens.add(node); } ... } Now the the test returns an exception! Planning and Managing Software Projects – Emanuele Della Valle
  • 17. JUnit – Setup ● The setup is done through @Before and @BeforeClass annotations – It allows to define the fixture ● Methods annotated with @Before are executed before the execution of each test case ● Methods annotated with @BeforeClass are the first to be executed Planning and Managing Software Projects – Emanuele Della Valle
  • 18. JUnit – Tear Down ● The tear down is done through @After and @AfterClass annotations – Used to destroy the fixture and reset the status before the test execution ● Methods annotated with @After are executed after the execution of each test case ● Methods annotated with @AfterClass are executed after the execution of all the test methods and all the @After annotated methods Planning and Managing Software Projects – Emanuele Della Valle
  • 19. Example (example4 - TreeNodeTest.java) public class TreeNodeTest{ private TreeNode root; private TreeNode child; @Before public void setup(){ root=new TreeNode(); child=new TreeNode(); root.addChild(child); } ... } Now we have to fix the code of the tests... Planning and Managing Software Projects – Emanuele Della Valle
  • 20. Example (TreeNodeTest.java) public class TreeNodeTest{ ... @Test public void shouldAddChildInTail(){ TreeNode secondChild = new TreeNode(); secondChild.setContent("content2"); root.addChild(secondChild); TreeNode lastChild = root.getChildren().getLast(); assertEquals(secondChild, lastChild); } @Test public void childShouldHaveTheParent(){ TreeNode parent = root.getChildren().get(0).getParent(); assertEquals(root, parent); } } Planning and Managing Software Projects – Emanuele Della Valle
  • 21. Test suite ● In order to execute the test cases a test suite class is required ● @RunWith and @SuiteClasses are the annotations that define a test suite: – @RunWith indicates the test runner (a class implementing org.junit.runner.Runner) – @SuiteClasses defines the list of the classes containing the test cases of the test suite ● It is also possible to use the Java program: org.junit.runner.JUnitCore.runClasses( TestClass1, TestClass2, ...); Planning and Managing Software Projects – Emanuele Della Valle
  • 22. Example (example5 - TreeNodeTestSuite.java) @RunWith(Suite.class) @SuiteClasses({TreeNodeTest.class, TreeNodeNegTest.class}) public class TreeNodeTestSuite{ } Planning and Managing Software Projects – Emanuele Della Valle
  • 23. Test Suite lifecycle @BeforeClass methods • @Before methods For each test: • @Test method • @After methods @AfterClass methods Planning and Managing Software Projects – Emanuele Della Valle
  • 24. JUnit – some best practices ● Write the tests before the tested code – Test-driven Development ● Put the test cases in the same package of the tested classes but in a different source folder – It enables the test of the protected methods ● Execute all the tests every time you change something! Planning and Managing Software Projects – Emanuele Della Valle
  • 25. References  JUnit Test Infected: Programmers Love Writing Tests http://junit.sourceforge.net/doc/testinfected/testing.ht m  JUnit Cookbook http://junit.sourceforge.net/doc/cookbook/cookbook.ht m  JUnit and EasyMock (Dzone RefCard) http://refcardz.dzone.com/refcardz/junit-and- easymock  JUnit Kung Fu: Getting More Out of Your Unit Tests http://weblogs.java.net/blog/johnsmart/archive/2010/ 09/30/junit-kung-fu-getting-more-out-your-unit-tests Planning and Managing Software Projects – Emanuele Della Valle