Anatomy of a unit test
What a JUnit unit test is made of: the test class, the @Test annotation, the fixture, the Arrange-Act-Assert plan, one test per behaviour, independent tests and a name that says what is checked.
- 24 cards
- 3 topics
- Free
The outline, topic by topic
Each topic is weighted the way the exam weighs it.
- Concepts
- Questions
- Sort and link
A few cards from the deck
Unit test: what is it?
Show the answer
A small program that runs a single unit of code (a method, a class) in isolation from the rest and checks its result automatically.
It answers pass or fail without anyone reading an output: it can therefore be replayed hundreds of times.
What is
compteurworth at the start of each test of this JUnit 5 class (default configuration)?
```java
class CompteurTest {
int compteur = 0;
@Test
void premier() {
compteur++;
assertEquals(1, compteur);
}
@Test
void second() {
compteur++;
assertEquals(1, compteur);
}
}`- 0: JUnit creates a new instance of the class for each test
- 0 for the first test run, then 1 for the next: the field keeps its value
- 1 for both: the initialisation is replayed after the increment
- A compile error: a field cannot be modified by two methods
Show the answer
0: JUnit creates a new instance of the class for each test
JUnit 5 instantiates the test class once per test method: an instance field is therefore fresh in each test and both assertions pass. A
staticfield would be shared and make one test depend on the other.In JUnit 5, a method becomes a test when it carries the … annotation; it is declared without a return value, so ….
Show the answer
In JUnit 5, a method becomes a test when it carries the @Test annotation; it is declared without a return value, so void.
A
@Testmethod that returns a value is skipped by JUnit 5: it is simply not run as a test.System under test: what is it?
Show the answer
The precise piece of code that a test calls in order to check its behaviour.
A test targets it alone: when the test fails, the culprit is looked for in that piece of code, not in the whole project.
This test always passes, even if
ajouterno longer does anything. What is the flaw?
```java
@Test
void ajouterUnLivre() {
Panier p = new Panier();
p.ajouter("Dune");
}`- It creates the basket in the test instead of in a @BeforeEach
- It contains no assertion: nothing can make it fail
- It is not public, so JUnit does not find it
- It calls only one method of Panier, which is not enough for a test
Show the answer
It contains no assertion: nothing can make it fail
A test passes as long as no exception escapes: without an assertion it proves nothing. For example
assertEquals(1, p.taille());is missing. A test method may perfectly well have no access modifier in JUnit 5.