Files
VV-ISTIC-TP3/exercises/assertions.md
2025-12-05 09:55:50 +01:00

42 lines
1.5 KiB
Markdown

# 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
1.
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
2.
assertEquals vérifie si les valeurs des objets sont identiques alors que assertSame vérifie si l'objet est identique.
Par exemple
```java
String s = "test";
assertSame(s,s);
assertEquals(s,s);
```
revoient true
alors que
```java
String s = "te";
String s2 = "test";
s += "st"; //sinon l'optimisation du compilateur Java met le même objet sur s et s2
assertSame("test",str+"st");
assertEquals("test",str+"st");
```
assertSame renvoit false, alors que assertEquals renvoit true
3.
4.
Cela permet de rendre les test plus uniforme, dans junit 5 on comprend mieux où exactement on attend l'exception.