Files
VV-ISTIC-TP3/exercises/assertions.md
2025-12-19 21:52:35 +01:00

1.6 KiB

On assertions

Answer the following questions:

  1. The following assertion fails assertTrue(3 * .4 == 1.2). Explain why and describe how this type of check should be done.

  2. What is the difference between assertEquals and assertSame? Show scenarios where they produce the same result and scenarios where they do not produce the same result.

  3. In classes we saw that fail is useful to mark code that should not be executed because an exception was expected before. Find other uses for fail. Explain the use case and add an example.

  4. In JUnit 4, an exception was expected using the @Test annotation, while in JUnit 5 there is a special assertion method assertThrows. In your opinion, what are the advantages of this new way of checking expected exceptions?

Answer

Les flottants sont codés en binaire avec des divisions de 2, certaines valeurs sont donc impossibles à avoir exactement en flottant, comme 1.2 et 0.4 Pour être sûr que 2 flottant sont identiques, il faut qu'ils soient passés par les mêmes opérations.

assertEquals vérifie si les valeurs des objets sont identiques alors que assertSame vérifie si l'objet est identique. Par exemple

String s = "test";
assertSame(s,s);
assertEquals(s,s);

revoient true alors que

String s1 = "un ancien string"; //sinon Java réutilise le même objet "test" pour s1 et s2
String s2 = "";
s1 = "test";
s2 = "test";
assertSame(s1,s2);
assertEquals(s1,s2);

assertSame renvoit false, alors que assertEquals renvoit true

Cela permet de rendre les test plus uniforme, dans junit 5 on comprend mieux où exactement on attend l'exception.