N
N
Nikolai Volynkin2015-05-15 11:21:46
Java
Nikolai Volynkin, 2015-05-15 11:21:46

How to run a series of JUnit tests strictly sequentially?

There is a series of tests. I want them to use some shared object. The first test calculates it, the second (and subsequent ones) require it for their work. It seems that, by default, tests are run in separate threads and the first test does not have time to complete by the beginning of the second. I know about it, it doesn’t fit,
because @Beforefor each test, another benchmark is hung and I don’t want to leave the first test without it.
Question: how to explicitly specify that all tests are executed sequentially or after the first one?

/** shared object */
Object a;

@Test() //succeeds
public void testFoo() {
    a = foo();
    Assert.assertNotNull(a);
}

@Test()
public void testBar() {
    Assert.assertNotNull(a); //fails
    b = bar(a); //null pointer exception
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
E
Evhen, 2015-05-15
@nick_volynkin

to start

public class JUnitTest {
  @BeforeClass public static void beforeClass() {}
  @Before public void before() {}
  @Test public void test1() { }
  @Test public void test2() { }
  @Test public void test3() { }
  @AfterClass public static void afterClass() { }
  @After public void after() { }
}

// Последовательность вызовов методов

JUnitTest.beforeClass();
JUnitTest test1 = new JUnitTest();
test1.before();
test1.test1();
test1.after();
JUnitTest test2 = new JUnitTest();
test2.before();
test2.test2();
test2.after();
JUnitTest test3 = new JUnitTest();
test3.before();
test3.test3();
test3.after();
JUnitTest.afterClass();

those. under each method marked as @Test will be called from a separately created class , thus achieving isolation between tests. That's why you have a == null in the second test.
if you want the object to be shared between tests, you need to create it as a static field.
and in my opinion, tests within the same class are called sequentially

N
Nikolai Volynkin, 2015-05-15
@nick_volynkin

Temporarily decided by adding @Beforeto the first test. @BeforeIt turns out that there can be more than one annotation .
But this still does not give a complete answer to the question.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question