1 / 70

J. Paul Gibson paul.gibson@it-sudparis.eu http://www-public.it-sudparis.eu/~gibson/

Les tests en orienté objet. J. Paul Gibson paul.gibson@it-sudparis.eu http://www-public.it-sudparis.eu/~gibson/ Bureau A 207, Le département LOgiciels-Réseaux. Thanks to: Christian Bac, Denis Conan & Jean-Luc Raffy. Les tests en orienté objet. I.Rappels sur les tests

cole
Télécharger la présentation

J. Paul Gibson paul.gibson@it-sudparis.eu http://www-public.it-sudparis.eu/~gibson/

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Les tests en orienté objet J. Paul Gibson paul.gibson@it-sudparis.eu http://www-public.it-sudparis.eu/~gibson/ Bureau A 207, Le département LOgiciels-Réseaux Thanks to:Christian Bac, Denis Conan & Jean-Luc Raffy Dr J Paul Gibson, TSP, Evry

  2. Les tests en orienté objet I.Rappels sur les tests II. Comment utiliser les modèles OO en UML? III. Étude de cas – médiathèque A) Préparation Tests de validation Tests d’intégration Tests unitaires B) Codage et Exécution Tests unitaires avec JUnit Tests d’intégration Tests de validation Dr J Paul Gibson, TSP, Evry

  3. I.Rappels sur les tests Validation Spécification Conception préliminaire Tests d’intégration Conception détaillée Tests unitaires Codage (système et tests) Le cycle en V préparation Codage et exécution préparation Codage et exécution préparation Codage et exécution Dr J Paul Gibson, TSP, Evry

  4. I.Rappels sur les tests Testing Consistency (not uniquely OO) • Tests are the main way of maintaining consistency in the documentation/models: • Natural Language Text (English/French) • (UML) models • (Java) Code • Comments in (Java) Code If you do not develop tests in parallel with code you risk having widespread inconsistency that is difficult to fix (particularly in large projects with lots of team members working on different phases of the development). NOTE: testingafter all the code isdevelopedisusually a badidea,but itisbetterthan no testingat all! Dr J Paul Gibson, TSP, Evry

  5. I.Rappels sur les tests Niveaux de test - pour chaque (sous)système Préparat ion exécution • Tests de validation • Tests d’intégration • Tests unitaires Système Sous-système Dr J Paul Gibson, TSP, Evry

  6. II. (OO) modeles en UML UML – les diagrammes Tests de validation • Niveau Application (spécification) • Diagramme des cas d’utilisation • Niveau Sous-Système(Analyse et conception) • test des associations, des agrégations (diagramme de classes) • multiplicité • création, destruction • test de séquences (diagramme de séquence et de communications) • construction d’un graphe de flot • test des exceptions contrȏlées • Diagramme des classes (ébauche) • Diagrammes de séquence/communications • Niveau Classes (conception détaillée) • Classes détaillées • Diagrammes de machine à états Tests d’intégration Tests unitaires Dr J Paul Gibson, TSP, Evry

  7. II. (OO) modeles en UML How to Use UML • A keyprinciplewithtestingisthat the tests shouldbederivedfrom (and be consistent with) the requirementsspecification. • The UML diagramsshould help us because: • if our tests are consistent with the UML then – provided the UML isvalidatedagainst the informallyexpressedneeds of the client – we have a good chance of properlytesting the system againstwhatisreallyrequired by the client/customer • the structure of the UML should correspond to the structure of the developed code – itis a bridge betweenwhatisrequired and how itis to beimplemented – sowecanre-use this design structure to structure our tests. Dr J Paul Gibson, TSP, Evry

  8. II. (OO) modeles en UML Use Case Diagrams – for each use case examine possible scenarios, and choose a subsetof alternative pathsfor testing. For example: Validation Use case1 Use case2 Use case3 Use case4 Dr J Paul Gibson, TSP, Evry

  9. II. (OO) modeles en UML The test sequence can be decided by looking at the tree-like structure of composition hierarchies. For example: Integration : composition tree Système Composition tree Note: in reality, one rarelysees a tree due to shared components and cyclicdependencies. However, one canalwaysfind a reasonabletreeabstractionfromanygiven composition hierachy. Dr J Paul Gibson, TSP, Evry

  10. II. (OO) modeles en UML Big Bang– system validation – « if the system works then it must be properly integrated? » Test at the system interface Integration : big bang approach • MAIN PROBLEMS: • Testingproduceserrors, but whatcausedthem? • Testing misses bugs • Testingstartsafter all components are coded Dr J Paul Gibson, TSP, Evry

  11. II. (OO) modeles en UML Top Down– test all interactions between components (fromroot to leaves). Integration : top down approach 1 3 2 4 6 5 7 8 Possibleintegration test sequence (depth first) Dr J Paul Gibson, TSP, Evry

  12. II. (OO) modeles en UML Top Down– the need for stubs (to replace as yetunimplementedlower-level components) In top down testing, wemaystart the tests before all components are coded. In such a case, wemay have to writestubs – pieces of dummy code thatsimulatebehaviourthatis not yetcoded. In OO, stubssimulatecalledmethods. Integration : stubs To test the integration between the mediatheque and the ficheEmprunt, we may have to write a stub which simulates part of the client’s behaviour Mediatheque FicheEmprunt Client Dr J Paul Gibson, TSP, Evry

  13. II. (OO) modeles en UML Bottom-Up– test all interactions between components (from leaves to root). Integration : bottom up approach 6 8 7 3 4 5 1 2 Possibleintegration test sequence (depth first) Dr J Paul Gibson, TSP, Evry

  14. II. (OO) modeles en UML Bottom-Up– the need for drivers (to replace as yetunimplementedhigher-level components) In bottom up testing, wemaystart the tests before all components are coded. In such a case, wemay have to writedrivers– pieces of dummy code thatsimulatebehaviourthatis not yetcoded. In OO, driverssimulatecallingmethods Integration : drivers Mediatheque To test the integration between the client and the ficheEmprunt, we may have to write a driver which simulates part of the behaviour of the mediatheque FicheEmprunt Client Dr J Paul Gibson, TSP, Evry

  15. II. (OO) modeles en UML • Il faut tester les invariants de chaqueclasse • Il faut tester la fonctionnalité de chaque méthode de chaque classe • Des classes avec des contraintesséquenciellessurl’activation des méthodes et leurs clients peuventavoir des erreurs de séquencement. • => Le comportementrequisdoitêtretesté en utilisant un modèle de machine à états Les tests unitaires Dr J Paul Gibson, TSP, Evry

  16. III. Etude de cas Comment Tester la Médiathèque? PrésentationSéquence 1 3 5 6 4 2 • A) Préparation • Tests de validation, e.g.: Emprunter • Tests d’intégration, e.g.: Emprunter • Tests unitaires, e.g.: Document • B) Codage et Exécution • 4. Tests unitaires avec JUnit • 5. Tests d’intégration • 6. Tests de validation Dr J Paul Gibson, TSP, Evry

  17. III. Etude de cas Comment Tester la Médiathèque? • Préparation • Tests de validation, eg: Emprunter • Tests d’intégration, eg: Emprunter • Tests unitaire, eg: Document • B) Codage et Exécution • Tests unitaire avec JUnit • Tests d’intégration • Tests de validation Dr J Paul Gibson, TSP, Evry

  18. III. Etude de cas – Préparation Tests de Validation Emprunter A validation test (is a black box test - usuallydone by the client - thatvalidates the (partial) behaviour of the whole system. The UML use case diagrams help us to identify good candidates for validation tests. Wewill test the emprunterfunctionality Dr J Paul Gibson, TSP, Evry

  19. III. Etude de cas – Préparation Tests de Validation Emprunter • Données d’entrée • client: peut être inscrit ou non; • emprunts: déja effectués par le client • • existe-t-il un emprunt en retard ? • • le nombre de documents empruntés correspond-il au nombre maximum de ce client ? • document: • existe? • • empruntable ou consultable?, • • déjà emprunté ou disponible? Dr J Paul Gibson, TSP, Evry

  20. III. Etude de cas – Préparation Tests de Validation Emprunter • Données de sortie • Emprunt accepté ou refusé. • Remarque: la définition des jeux de tests de validation pour le cas d’utilisation emprunterdocument permet de soulever au moins les questions suivantes (à poser au client): • • un abonné qui n’est pas à jour de sa cotisation peut-il tout de même emprunter un document? • • doit-il être considéré comme un client au tarif normal tant qu’il n’a pas renouvelé son abonnement? • • ou doit-il se réabonner avant de pouvoir emprunter un document? • D’une manière générale, la préparation des jeux de tests de validation permet de lever les ambiguïtés et les vides de la spécification. • NOTE : Plus les tests sont préparés tôt et moins les corrections coûtent chères Dr J Paul Gibson, TSP, Evry

  21. III. Etude de cas – Préparation Tests de Validation Emprunter Table de décisions Dr J Paul Gibson, TSP, Evry

  22. III. Etude de cas – Préparation Tests de Validation Emprunter To illustrate the testing process, we will treat the first 2 test cases • Test 1 - Client n'est pas inscrit • Test Code Steps: • IntialisedummyMediatheque • Check state of currentMediatheque(includingstatistics) • Attempt to « emprunter » a document for a client whodoes not exist • Check state of currentMediatheque(includingstatistics) Dr J Paul Gibson, TSP, Evry

  23. III. Etude de cas – Préparation Tests de Validation Emprunter • Test 2 - Client possède un emprunt qui est en retard • Test Code Steps: • IntialisedummyMediatheque • Check state of currentMediatheque(includingstatistics) • Authorise « emprunter » of a document for a client • Advance the date sothat the previous« emprunt » isnowpastits deadline • Attempt to « emprunter » by the same client beforethey return the document thatispastits deadline • Check state of currentMediatheque(includingstatistics) Dr J Paul Gibson, TSP, Evry

  24. III. Etude de cas Comment Tester la Médiathèque ? • Préparation • Tests de validation, e.g.: Emprunter • Tests d’intégration, e.g.: Emprunter • Tests unitaires, e.g.: Document • B) Codage et Exécution • Tests unitaires avec JUnit • Tests d’intégration • Tests de validation Dr J Paul Gibson, TSP, Evry

  25. III. Etude de cas –Tests de Validation - Codage et Execution Validation Tests Even if oursystem is not yetcompletelydeveloped, wecanwrite the code for the validation tests; and compile and run the tests once the system iscompletelydeveloped. For thisexample, wewill code the validation test as a JUnit test on the mediatheque class. NOTE: A validation of the overall system isoftenknown as an acceptance test; and canbethought of as a system unit test. Dr J Paul Gibson, TSP, Evry

  26. III. Etude de cas –Tests de Validation - Codage et Execution @Before publicvoidsetUp() throws Exception { // un test de validation est un test unitaire sur la classe Mediatheque m1= newMediatheque("mediatheque test"); Genre g = new Genre("Test_nom1"); Localisation l = new Localisation("Test_salle1","Test_rayon1"); Document d1 = newVideo("Test_code1",l, "Test_titre1", "Test_auteur1", ""); Document d2 = newVideo("Test_code2",l, "Test_titre2", "Test_auteur2", "Test_annee2" ,g, "Test_duree2", "Test_mentionLegale2"); m1.ajouterDocument(d1); m1.metEmpruntable("Test_code1"); m1.ajouterDocument(d2); m1.metEmpruntable("Test_code2"); CategorieClient cat = new CategorieClient("Test_Cat1", 10, 1.5, 2.5, 3.5, true); Client c1 = new Client("Test_Client_Nom1", "Test_Client_Prenom1", "Test_Client_Address1",cat); m1.inscrire(c1); Client c2 = new Client("Test_Client_Nom2", "Test_Client_Prenom2", "Test_Client_Address2",cat); } @After publicvoidtearDown() throws Exception {m1 = null;} Dr J Paul Gibson, TSP, Evry

  27. III. Etude de cas –Tests de Validation - Codage et Execution Test 1 - Client n'est pas inscrit /** * Document TEST 1<br> * Client n'est pas inscrit */ @Test \\ @Test (expected= OperationImpossible.class) – if weexpect an exception publicvoidclientPasInscrit( ) throwsOperationImpossible, InvariantBroken{ // assertions on state of m1 beforeemprunter m1.emprunter("nom", "prenom", "Test_code1"); // assertions on state of m1 afteremprunter } Dr J Paul Gibson, TSP, Evry

  28. III. Etude de cas –Tests de Validation - Codage et Execution Test 2 - Client n'est pas sans retard /** * Document TEST 2<br> * Client n'est pas sans retard */ @Test \\ @Test (expected= OperationImpossible.class) – if weexpect an exception publicvoidclientAvecRetard( ) throwsOperationImpossible, InvariantBroken{ // assertions on state of m1 before emprunter m1.emprunter("nom1", "prenom1", "Test_code1"); Datutil.addAuJour(7); Datutil.addAuJour(7); m1.emprunter("nom1", "prenom1", "Test_code2"); // assertions on state of m1 after emprunter } Dr J Paul Gibson, TSP, Evry

  29. III. Etude de cas Comment Tester la Médiathèque ? • Préparation • Tests de validation, e.g.: Emprunter • Tests d’intégration, eg: Emprunter • Tests unitaires, e.g.: Document • B) Codage et Exécution • Tests unitaires avec JUnit • Tests d’intégration • Tests de validation Dr J Paul Gibson, TSP, Evry

  30. III. Etude de cas – Préparation Tests d’intégration Emprunter • The operation« emprunter » requiresco-ordinationbetween the • client, • mediatheque, • document, and • ficheEmpruntobjects We wish to verify that the traces (of communication) between the objects involved in the collaboration, as specified in UML, are executed by the implementation (in Java), following the specified temporal ordering. These tests can be derived from the communications and/or sequence diagrams … Dr J Paul Gibson, TSP, Evry

  31. III. Etude de cas – Préparation Tests d’intégration Emprunter In the communications diagram, the temporal orderisspecified by the numbering Dr J Paul Gibson, TSP, Evry

  32. III. Etude de cas – Préparation Tests d’intégration The co-ordinationbetween the Client and the Document: Integration Test 1 An « emprunt » isnot authorisedbecause the document is not « empruntable » IntegrationTest 2 An « emprunt »is not authorisedbecause the document is« emprunté » Integration Test 3 Empruntisauthorised Emprunter 1 2 3 4 5 6 6.1 6.2 6.2.1 6.3 6.3.1 6.4 6.4.1 6.5 6.6 6.6.1 Note: integration tests do not usuallyrequire all components to beimplementedfully Dr J Paul Gibson, TSP, Evry

  33. III. Etude de cas –Tests d’Integration - Codage et Execution Emprunter • Integration Test1 - An « emprunt » is not authorisedbecause the document is not empruntable • Construct a document,andmakeit not Empruntable • Construct a client • Construct a FicheEmprunt for the client and document • Check that: • the system handles the exceptional case in a meaningful way • the client and document states/statistics have not been changed Dr J Paul Gibson, TSP, Evry

  34. III. Etude de cas – Préparation Tests d’intégration Emprunter • Integration Test 2 Design: An « emprunt » is not authorisedbecause the document is« emprunté » • Construct a document, whichis empruntable andemprunté • Construct a client • Construct a FicheEmprunt for the client and document • Check that: • the system handles the exceptional case in a meaningful way • the client and document states/statistics have not been changed Dr J Paul Gibson, TSP, Evry

  35. III. Etude de cas – Préparation Tests d’intégration Emprunter • Integration Test 3: Emprunt isauthorised • Construct a document, whichis empruntable and not emprunté • Construct a client • Construct a FicheEmprunt for the client and document • Check that the system handles the exceptional case in a meaningful way • Check that: • the tarif and duree des emprunts are as required • the client and document states/statistics have been updated as required Dr J Paul Gibson, TSP, Evry

  36. III. Etude de cas Comment Tester la Médiathèque ? • Préparation • Tests de validation, e.g.: Emprunter • Tests d’intégration, e.g.: Emprunter • Tests unitaires, e.g.: Document • B) Codage et Exécution • Tests unitaires avec Junit • Tests d’intégration • Tests de validation Dr J Paul Gibson, TSP, Evry

  37. III. Etude de cas –Tests d’Integration - Codage et Execution Emprunter Integration Test1 Code: Verify correct co-ordination by FicheEmprunt • Construct a document, and makeit Empruntable • Construct a client • Construct a FicheEmprunt for the client and document using a dummymediatheque • Check that the tarif and “duree des emprunts” values for the FicheEmprunt are as required • Check that the client and document states have been updatedcorrectly We should do the same for integration tests 2 and3 Dr J Paul Gibson, TSP, Evry

  38. III. Etude de cas –Tests d’Integration - Codage et Execution Emprunter Integration Tests: Current Development Status • Weneed to analyze the status of each of the system classes in order to decide on an integrationtestingstrategyconcerning the coding of stubs and drivers (whererequired): • Completed • Partial • Not yetimplemented Dr J Paul Gibson, TSP, Evry

  39. III. Etude de cas –Tests d’Integration - Codage et Execution Emprunter IntegrationTest 1 • Completed • Partial • Not yetimplemented Analysis: itistoosoon to code the integration tests as itwouldrequire extensive development of stubs and drivers Dr J Paul Gibson, TSP, Evry

  40. III. Etude de cas Comment Tester la Médiathèque ? • Préparation • Tests de validation, e.g.: Emprunter • Tests d’intégration, e.g.: Emprunter • Tests unitaires, e.g.: Document • B) Codage et Exécution • Tests unitaires avec JUnit • Tests d’intégration • Tests de validation Dr J Paul Gibson, TSP, Evry

  41. III. Etude de cas – Préparation Tests Unitaires The Document class • Wewill use the following UML diagrams to « derive » our unit tests for the Document class: • Class Diagrams • State machine diagrams • Wemayalsoneed to use the original naturallanguagetext. • Weshould not have to examine the Java code Document.java, but canjust call the code using the Document.class file – thisisblackboxtesting. • Wemayneedaccess to the documentation for the code in order to understand code propertiesthat are not specified in the UML models. • NOTE: If documentation ispoorthenwewill have to examine the code in order to be able to guaranteethatour tests compile and executecorrectly. Dr J Paul Gibson, TSP, Evry

  42. III. Etude de cas – Préparation Tests Unitaires The Document class The high-level class diagramcanbepartitionedsothatwe abstract awayfrom the classes that are not directly « connected » to the Document Dr J Paul Gibson, TSP, Evry

  43. III. Etude de cas – Préparation Tests Unitaires The Document class Wetest only the public attributes and operations/methods – following the blackboxapproach Weshould first examine the safetyinvariant … if itis not in the UML model thenweneed to addit. Dr J Paul Gibson, TSP, Evry

  44. III. Etude de cas – Préparation Tests Unitaires The Document class The invariantpropertyisdefined on the attributes of the class in order to saywhen a Document instance/objectis in a SAFE state, i.e. a state whichismeaningful/allowable. Here, the invariant should « include »: Emprunté => empruntable ANDnbEmprunts >=0 A formal interpretation that needs validation with the client Weshouldlinkthis (invariant) requirement to the original text, where possible: « La médiathèque contient un certain nombre de documents disponibles à la consultation ou à l’emprunt » Dr J Paul Gibson, TSP, Evry

  45. III. Etude de cas – Préparation Tests Unitaires The Document class BUT, these are not public So we have a test design choice – • 1)extend the Document class by adding a public invariantmethod: • (a) creating a new subclass (and make variables protected), or • (b) editing/updating the Document class • OR • 2)use public methods – directly in the testing code - that are equivalent to testing the invariant and are guaranteed not to change the state of the object (Document) beingtested (e.g. estEmpruntable and estEmprunte.) Dr J Paul Gibson, TSP, Evry

  46. III. Etude de cas – Préparation Tests Unitaires The Document class All design decisionsinvolve compromise. QUESTION: Can yousee the advantages/disadvantages of each option for specifying the invariant property? • In this example, we choose to pursue option 1 (b) -Edit the Document class, because - • It is good practice in OO development to have invariants specified for all classes, and • It is the « simplest » coding option for « Java beginners » Dr J Paul Gibson, TSP, Evry

  47. III. Etude de cas – Préparation Tests Unitaires Document Now, let’sconsider the dynamicbehaviourspecified by the state machine. The first thingisthatthe initial state (constructed) must beSAFE. Thenwe check thatall subsequent states are SAFE. Dr J Paul Gibson, TSP, Evry

  48. III. Etude de cas – Préparation Tests Unitaires Document • Test1: check that the construction of a Document respects the invariant • Createa DocumentTest class with a single mainmethod for testing a concrete instance of a Documentsubclass – • Video, • Audio, • Livre • Create a testmethodthatgetscalled in the mainmethod. • Ensurethat the test canbechecked– • output results to screen • printresults to file • includetest oracle code thatknowswhatthe resultsshouldbe and assertsthesewhenthe test executes, automating the test process Dr J Paul Gibson, TSP, Evry

  49. III. Etude de cas – Préparation Tests Unitaires Document Test 2: Check all reachable states to be SAFE, i.e. respect the invariant Code Design: Complete state coveragecanbeachieved by a single trace of events/operations/method calls aftercreation – metEmpruntable() emprunter() NOTE: Testing all states respect the invariant does not check the correct temporal behaviour of the Document class …We will see this problem later with Test4 Dr J Paul Gibson, TSP, Evry

  50. III. Etude de cas – Préparation Tests Unitaires Document • We need to write at least one test for each public operation/method of the Document class. • For conciseness, we illustrate this by looking at the single Emprunter operation • « emprunter : … Pour tous les documents, les statistiques sont mises à jour à savoir : le nombre d’emprunts de ce document, le nombre d’emprunts de ce type de document et le nombre d’emprunts total » Test3 - check statistics are updatedcorrectly Code design steps:« emprunt » a document 5 times and, each time, check that the individual document « statistiques » are incremented. At the end of the loop, check that the total « statistiques » have increased by 5. Dr J Paul Gibson, TSP, Evry

More Related