1

I have a JUnit 5 test class with a non static String attribute (value).
The test class has 2 test methods, which are executed in a defined order (for question order does not matter).
The first executed test method sets the String attribute to "Test".
But when second test method is executed the String attribute is null instead of "Test".

Why is it like this in JUnit 5?
Beside making the String attribute static, can I handle this in another way?

Here is some sample code:

@TestMethodOrder(OrderAnnotation.class)
class Junit5Test {
  private String value;

  @Test
  @Order(1)
  void setValueTest() {
    this.value = "Test";
    assertNotNull(this.value);
  }

  @Test
  @Order(2)
  void readValueTest() {
    // This test fails, because value is null. Why?
    assertNotNull(this.value);
  } 
}
Elmar Brauch
  • 1,286
  • 6
  • 20

1 Answers1

1

For each test method a new instance of the test class is created, so the change of state will not be preserved between invocations, independently of the ordering of test methods.

See Does Junit reinitialize the class with each test method invocation?

As for "handling this another way", I would recommend against it. Unit tests should be independent.

Tests should not depend on each other. One test should not set up the conditions for the next test. You should be able to run each test independently and run the tests in any order you like. When tests depend on each other, then the first one to fail causes a cascade of downstream failures, making diagnosis difficult and hiding downstream defects.

Robert C. Martin Clean Code: A Handbook of Agile Software Craftsmanship, Chapter 9.

SDJ
  • 4,083
  • 1
  • 17
  • 35
  • Thanks, that answers first part of my question. But is there a way to pass attribute from one test to another? JUnit has `@ParameterizedTest` and `@ValueSource` annotations, so is there also something to export a value to these sources? – Elmar Brauch Dec 18 '20 at 21:41