JUnit And Latches
// 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();
}
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.
Related Questions
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM