0% found this document useful (0 votes)
27 views10 pages

Quiz 1

Uploaded by

Gonna Be
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
27 views10 pages

Quiz 1

Uploaded by

Gonna Be
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 10
02108/2028, 18:25 Using test aulomation practices to write effective unit tests - OpenClassrooms DPENCLASSROOMS Quy ‘Accueil > Cours > Use Testing in Java to Achieve Quality Applications > Quiz : Using test automation practices to write effective unit tests Use Testing in Java to Achieve Quality Applications @ heures af Moyenne Mis & jour le 04/0 Using test automation practices to write effective unit tests Vous n'avez pas validé ce quiz. Vous n'avez pas atteint le seuil de validation de cet exercice, c'est-a-dire 70%. Ce n'est pas tres grave car vous pourrez refaire le quiz dans 24h. Compétences évaluées © write effective unit tests by using test automation best practices Description ‘A quiz covering the testing pyramid, basic JUNit unit test structure, annotations, Hamcrest matchers, and interpreting failing tests. Question 1 Which of the following statements are true of TDD? Attention, plusieurs réponses sont possibles. hitps:fopenclassrooms, comficourses'5661466-use-testing-mjava-to-achieve-qualiy-applications/exercisesI3461 ato 02/08/2028, 18:25 Using est automation practices to writs el clive ui tests - OpenClassrooms Vv @ You to start by writing a failing test before you write your code. O You art by impler ting just enough de to begin w g a test. XC typically, you should write multiple tests for each method. xaty y, you should write one unit test thod. Test-driven development, as the name suggests, requires you to let your tests guide what and how your code behaves. It is often called test-first development as you are encouraged to write a failing test before you start writing any code. This way, your tests always lead you in deciding what real code to implement. The unit tests you write should target the public methods of the classes you write, and should be used to explore the range of possibilities which exist for caling that particular method. Therefore, it is usually considered lazy if you only write one test per method. @ Question 2 Imagine you're working in a small team and a colleague shows you some of their code and review comments. First, you look at the class under test, called Person: java 1 public elas Person ¢ 2 private string firstnanes 3 private string lastvano; 4 5 public Person(String FirstNane, String lastNane) 6 this. FirstNane Nane; 7 ‘this.lastNane = lastWane; 8 9 30 public String getFulINane() { u return String. format ("Ks Xs", firstilane, 1 Rm) B) Your colleague shows you their JUnit 4 unit test for this Person class : java 1 import Per 2 import org. junit.*; 3 4. @Runhith(BlockUnitaclassRunner.class) 5 public class Persontest ¢ 6 7 If check that person.getFullNane() works 8 public static void getFulINane_shouldReturntheFsi rt 8 11 nevange 10 String expected = "Katherine Janelay"; a Person personUnderTest = new Person("Katherine", “Janelay"); 2 UT het B String fullNane = person.getFullNane(); hitps:fopenctassrooms, comlcourses'661466-use-testing-mjava-to-achieve-qualiy-applications/exercises/3461 20 (02108/2028, 18:25 Using test aulomation practices to write effective unit tests - OpenClassrooms 4 J] assert a5 Boolean testIsSuccessful = fulINane.equals (expected) ; 16 assert( testissuccessful ) v System. out.printIn(*Passed: “+ testTsSuccessful ) 13} 9 20 public static void main(stringt] args) ¢ a getful INane_shouldReturnTheFirstandLastNane_whenAPersonHiassot 2} 2B) Which of the following comments about this code are correct? Attention, plusieurs réponses sont possibles. O The runni er class should be repl jaced with 3unitRunner. class VG The @rest annotation is missing V G The assertion method is not suited for testing. XO Thete shouldn't be called from the main(String] args) The reason you use a framework like JUnit is that it simplifies test writing and hanales reporting on their success so you can focus on proving the quality of the code under test. The Block JUnit4ClassRunner used here is acceptable. However, it's the default runner used by JUnit (if you do not provide a custom runner), so it is redundant to explicitly declare it. JUnit's @Test annotation ensures that the annotated method is treated as a test and reported on. The success of your test's assertion will decide whether or not the test passes. You don't need to explicitly call that test method and write code to decide whether it passes or fails. You also don't need to declare a custom runner with @RunWith ; itis sufficient to annotate your test methods with Gtest Confusingly, Java itself provides an assert (Boolean condition) system function, which is not intended for JUnit tests. it throws an Assertionérror and terminates your program if the boolean argument does not evaluate to true. When testing for boolean or other values, you should not confuse this with assertion classes intended for use in your JUnit tests; such as org. junit.Assert.assertTrue(Boolean condition) and Hamerest’s matchers. hitps:fopenclassrooms, comficourses'5661466-use-testing-mjava-to-achieve-qualiy-applications/exercises/3461 3it0 02108/2028, 18:25 Using test aulomation practices to write effective unit tests - OpenClassrooms Question 3 What red-green-refactoring? O A technique to mark code via highlighting. Poor quality code is marked in red, and once fixed, should be marked in green for the code reviewer to check. ing your code is called refactoring Vv © Atechnique where you start with a failing test in red, then write code to make it pass to green. You can then improve and modify the code while checking if your changes pass the test via refactoring ts in green. You O A testing library that enables you to highlight failing tests in red and passing de in the failing tests until it turns green. begin refactoring your © A design pattern for a factory class which can start your tests een) and stop you them (red) 0 you can take the time to refactor them. Red-green-refactoring is a technique for TDD based on the metaphor of a traffic light. If you start with 2 failing test, most IDEs will show you a red failure telling you to stop make that test pass by builaing an expedient solution. Once you have a passing test, you are free to improve the quality of your solution knowing that if you break something, your test will turn red again. Question 4 Which of the fol wing is true of Hamcrest matchers? Attention, plusieurs réponses sont possibles. Vv G Individual Hamcrest matchers can be combined to express more complex assertions. Vv G Hamcrest matchers allow you to write assertions in more natural-sounding language. © Aamerest's matchers are more readable, but they don't cover the full range of JUnit assertions xo merest matchers are only available in English. Hamerest is designed to enable testers to express complex assertions by chaining together its matchers. This way, they can form more complex assertions about the actual behavior of your class under test. JUnit's assertions assert primitive statements using unnatural sounding methods such as assertEquals and assertTest. Question 5 hitps:fopenclassrooms, comficourses'661466-use-testing-mjava-to-achieve-qualy-applications/exercises/3461 4n0 02/08/2028, 18:25 Using test aulomation practices to write effective unit tests - OpenClassrooms Based on the testing pyramid, which of the following is true of unit tests? Attention, plusieurs réponses sont possibies. Vv @ They should make up the majority of your tests. O They test whether XG They focus on testing whether the di n interact as expected. V G@ They check that each individual class in your code performs as expected, The biggest section at the base of the pyramid is unit tests. These test individual classes and check that each one keeps its promises. They should be extremely quick, which means you can run a lot of them without having to sit around and wait for results. If you've broken something, you know about it fast and early. Since they only test individual classes, they can't tell you if everything in your app is working together correctly. That's where integration and system tests come in. Question 6 Have alook atthe setup() method in this test class: jova public PersonTest private Person personUnderTest; public void setup() ¢ derTest = new Person("Billy’ 1 2 3 4 5 6 7 8 // Your @Test methods go here: 9 You want to test the Person class, and arrange a new instance of it for each test method. Which of the following JUnit annotations would you use? V® @efore @after oO @BeforeClass ° @FterClass Oo @ForEveryMethodTestThat hitps:fopenclassrooms. comficourses'5661466-use-testing-mjava-to-achieve-qualiy-applications/exercisesI3461 5110 0210872023, 1825 Using test automation practices to write effective unit tests - OpenClassrooms It is usual to find that tests for a given class require some similar set up to arrange them for testing. JUnit 4 provides the @Before annotation for this. @Before marks a particular instance method on your test class, so that JUnit knows that it should run the test before each @Test annotated method is run. In this case, this is where you make sure that each test has a new instance of your personUnderTest to test with, Don't confuse this with @BeforeClass, which is used to annotate a static method that should be run before the first test method is run, @AfterClass similarly runs a static method after ail the tests ina class have completed running. Similarly, @After is used to run an instance method after each test method has run. @ForEveryMethodTestThat doesn't actually exist. @ Question 7 Have a look at this JUnit test method: java 1 Glest(expected = L0Exception. class) 2 public void readrile_shouldNotReadaFile_ifitDoesNotexist() throws TOException 3 String content = classUnderTest .readrile("/non/existant/path/to/File”) 4 assertéquals( content, 5) Which of the following situations will result in a passing test? O The value of content is an empty string O The calito classUnderTest.readFile() results in a custom BadFileE: V ® Thecallto classUnderTest.readFile() results in an IOException. et to an em © An exception is thrown and content is O The to classUnderTest.readFile() does not result in an ]OException To test that your CUT throws a particular exception for a negative scenario, you canuse @Test and pass it a special argument of expected with a value set to a particular Throwable exception class. JUnit will then pass the test if the method fails by throwing that particular exception, and not for any other. If your CUT throws an exception when you call a method in the ACT stage, it will interrupt the flow: before it gets to any subsequent asserts. This happens at line 3, and so the assert at line 4 is never reached and does not impact whether this test passes or fails. Question 8 Now have a look at this test method: hitps:fopenclassrooms, comficourses'5661466-use-testing-mjava-to-achieve-qualiy-applications/exercisesI3461 ano 02/08/2028, 18:25 Using test aulomation practices to write effective unit tests - OpenClassrooms java 1 gTest(tineout = 1¢08) 2 public void solveEquation_shouldReturnACorrectSolution_ForAConplexQuadr lon = underTe: ‘Ive (EQUATION) ; olution, expectedSolution) Which one of the following scenarios result in the test passing? O The s under tes rectly solves the equation in 1000 seconds V ® The class under test correctly solves the equation in up to 1 second, O The test completes faste than the time specified in the O The test method takes ex; ly the amount of time To make sure that your tests do not slow down to an unacceptable level, you can pass @Test the timeout argument with a value specified in miliseconds; that's in 1000th’s of a second. If the test does not complete and satisfy its assertions in this time, it will automatically fail. G@Test( timeou' 200) will only pass if the test completes and all assertions are passed in the specified time. Question 9 Which Maven plugin would you use to protect your code against standard coding mistakes (which may result in bugs)? Attention, plusieurs réponses sont possibles. v G Checkstyle O Jacoco XO FinaBugs O surefire Both Checkstyle and FindBugs perform static analysis on your code to inspect its structure and detect styles which are undesirable. FindBugs targets a known set of programming styles and inconsistencies which may result in issues. £4, it's buggy and inconsistent to use a variable after identifying that it contains a null, Checkstyle also has a large corpus of structural styles it can look for, which you can configure in a checkstyle.xml. Teams also use this to ensure a consistent style of coding against all their codebases. Many of the styles provided can help you identify if you're violating a convention which usually helps you avoid bugs. hitps:fopenclassrooms, comficourses'5661466-use-testing-mjava-to-achieve-qualiy-applications/exercisesI3461 710 (02/08/2028, 18:25 Using est automaton practices to wits effective unl tests - OpenClassroams The other two plugins are extremely useful and serve different purposes. Jacoco is good for testing how much of your codebase has been supported by unit tests. Surefire is great at reporting on those tests which do exist, Question 10 Look at the following Surefire HTML test report: © [essere 2 ir Pp 2 se ie Test Cases CCalculatortest Failure Details On Sa rio oR ent nrars re! Teinasicstn: eed ter 650 lien | epee Surefire HTML Test Reoort Based on this report, which of the following is true? Attention, plusieurs réponses sont possibies. V @ Aclass named CalculatorTest failed because one of its tests took longer than 1000ms. _returnsThe' TwoNegativeNumbers() O The only passing test m XC only 50% of the tests in CalculatorTest passed, XG The test failed at line 68 of the CalculatorTest class. O The tes d because of an ex n thrown by oul You're looking at the result of a timed-out test with @Test(timeout = 1000) . This is because the following exception and error message is in your test results: org. junit.runners.model.TestTimedoutException: test timed out after 1600 milliseconds This TestTimedoutexception was thrown by JUnit and not the class under test. hitps:fopenclassrooms. comicourses'5661466-use-testing-mjava-to-achieve-qualiy-applications/exercises/3461 ano (02/08/2028, 18:25 Using est automaton practices to wits effective unl tests - OpenClassroams If you look at the Failure Details section, you can see that it occurred in the com.openclassrooms.testing.CalculatorTest class at line 68 (the bit in blue). You could even click on this to see the source from here. You can also see in the failure details that the red cross is next to add_returnsTheSum_OfTwoNegativeNumbers; this is the name of the @Test annotated method which failed. At the top of this report, you can also see that only 50% of tests passed. Et si vous obteniez un dipléme OpenClassrooms ? «Formations jusqu’a 100 % financées * Date de début flexible ‘* Projets professionnalisants * Mentorat individuel Trouvez la formation et le financement faits pour vous Comparez nos types de formation improve code confidence with build tools Label your tests with advanced JUnit. and test report plugins annotations Le professeur Raf Gemmal Technical leader, Agile coach, solutions architect, and full-stack polyglot ‘OPENCLASSROOMS v ‘opPORTUNITES. v hitps:fopenclassrooms, comficourses'5661466-use-testing-mjava-to-achieve-qualiy-applications/exercises/3461 sno 02108/2028, 18:25 Using test automation practices to write effective uni ests - OpanClassrooms ADE v POUR LES ENTREPRISES v EN PLUS v ® Frangais v OO® a, Télécharger dans ‘App Store hitps:fopenclassrooms, comficourses'5661466-use-testing-mjava-to-achieve-qualiy-applications/exercises/3461 s0n10

You might also like