WillGetItDunn
WillGetItDunn

Reputation: 79

JUnit5: make multiple tests operate on the same object

I want to set up my JUnit5 tests to all operate on the same object. I read large files to use as test data, so I would prefer to read it once and utilize that same data for the rest of the tests.

I've created the following as a simple example where I try to achieve this using a static object ("list") (does not work):

import java.util.List;
import java.util.ArrayList;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;

class ExampleTest {

  // Single list object to be modified and accessed by the tests
  private static List<String> list = new ArrayList<String>();

  @BeforeAll
  static void setUpBeforeClass() throws Exception {
    // None
  }

  @Test
  final void addFoo() {
    list.add("foo");
  }

  @Test
  final void addBar() {
    list.add("bar");
  }

  @Test
  final void printList() {
    System.out.println(list.toString());
    assert(list.toString().equals("[foo, bar]"));
  }
}

The result of this is a failure of printList() where the list is empty instead of containing [foo, bar].

I have been able to make this work is by moving the methods that add data into the @BeforeAll:

  private static List<String> list;

  @BeforeAll
  static void setUpBeforeClass() throws Exception {
    list = new ArrayList<String>();
    list.add("foo");
    list.add("bar");
  }

But having the data importing methods as tests separate from @BeforeAll would be preferred.

@TestInstance(TestInstance.Lifecycle.PER_CLASS) did not work either.

Upvotes: 0

Views: 646

Answers (2)

WillGetItDunn
WillGetItDunn

Reputation: 79

The issue was with the JUnit method ordering (as noted by Abhijay). Utilizing @TestMethodOrder as described in the JUnit5 documentation to appropriately order the tests gave the desired result:

import java.util.ArrayList;
import java.util.List;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.TestMethodOrder;
import org.junit.jupiter.api.MethodOrderer;

@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
class ScratchTest {

  private static List<String> list = new ArrayList<String>();

  @BeforeAll
  static void setUpBeforeClass() throws Exception {
    // None
  }

  @Test
  @Order(1)
  final void addFoo() {
    list.add("foo");
  }

  @Test
  @Order(2)
  final void addBar() {
    list.add("bar");
  }

  @Test
  @Order(3)
  final void printList() {
    System.out.println(list.toString());
    System.out.println(list.toString().equals("[foo, bar]"));
    assert(list.toString().equals("[foo, bar]"));
  }
}

Upvotes: 1

Abhijay
Abhijay

Reputation: 328

Use @FixMethodOrder annotation. Refer to this article for example : https://www.mkyong.com/unittest/junit-run-test-in-a-particular-order/

Upvotes: 1

Related Questions