JUnit 和锁存器

JUnit and Latches

// 根据要求改进描述 //

代码工作正常,如下所示。但是如果我将一个 assert(Latch) 从 testA 移到 testB;断言失败。不管我给它多少延迟。

我也做了这个实验:如果我创建一个新的闩锁并让其中一个@Test 方法对其进行倒计时,另一个@Test 方法则看不到它倒计时!

@FixMethodOrder 没有帮助。

我试图用不同的方法拆分测试,但由于与共享的客户端连接以及事件顺序,我还需要保持一些同步。

谢谢

@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();

}

我想我自己找到了答案:

JUnit 在单独的测试实例中运行每个测试 class。因此变量(锁存器)不在测试之间共享。

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