Ad

JUnit And Latches

- 1 answer

// improving the description as requested //

The code works fine as it is below. But if I move one assert(Latch) from testA to testB; the assertion fails. No matter how much delay I give it.

Also I did this experiment: if I create a new latch and let one of the @Test methods count it down, the other @Test method does not see it counted down!

The @FixMethodOrder did not help.

I am trying to split the test in different methods, but I also need to keep some synchronization because of the connection to the client that is shared and also sequence of events.

thanks

@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class IBClientTest implements XStrategy {

private XBroker broker = new IBXClientC();
private final CountDownLatch connectedClient = new CountDownLatch(1);
private final CountDownLatch receivedTICK = new CountDownLatch(1);


@Test
public void testA() throws InterruptedException {

    broker.connect();
    broker.startStrategy(this);
    assertTrue(connectedClient.await(2, TimeUnit.SECONDS));
    assertTrue(broker.isConnected());

    XInstrument instr1 = XInstrument.fromString("EUR/USD");
    XInstrument instr2 = XInstrument.fromString("GBP/USD");
    Set<XInstrument> set = new HashSet<>();
    set.add(instr2);
    set.add(instr1);
    broker.subscribeToInstruments(set);

    assertTrue(receivedTICK.await(2, TimeUnit.SECONDS));

    broker.disconnect();

}

@Test
public void testB() throws InterruptedException {

}

// invoked by broker
@Override
public void onStart(XBroker broker) {

    connectedClient.countDown();
}

@Override
public void onStop() {
}

// invoked by broker
@Override
public void onTick(XInstrument instrument, XTick tick) {

    receivedTICK.countDown();

}
Ad

Answer

I think I found the answer myself:

JUnit runs each test in a separate instance of the test class. Hence the variable (latches) are not shared between tests.

JUnit is designed to work best with a number of small tests. It executes each test within a separate instance of the test class.

Ad
source: stackoverflow.com
Ad