@@ -198,6 +198,10 @@ public static Builder builderForNonStartableContext() {
198
198
* @throws Exception if there is an error closing the resources
199
199
*/
200
200
public void close () throws Exception {
201
+ callCloseables (closeables );
202
+ }
203
+
204
+ private static void callCloseables (List <AutoCloseable > closeables ) {
201
205
for (int i = closeables .size () - 1 ; i >= 0 ; i --) {
202
206
try {
203
207
closeables .get (i ).close ();
@@ -246,6 +250,7 @@ public static class Builder {
246
250
protected boolean configOverrideCalled = false ;
247
251
protected Function <BrokerService , BrokerService > brokerServiceCustomizer = Function .identity ();
248
252
protected WithMockZooKeeperOrTestZKServer withMockZooKeeperOrTestZKServer ;
253
+ protected PulsarTestContext otherContextToClose ;
249
254
250
255
/**
251
256
* Initialize the ServiceConfiguration with default values.
@@ -429,7 +434,15 @@ public Builder reuseSpyConfig(PulsarTestContext otherContext) {
429
434
* The other PulsarTestContext will be closed when this one is closed.
430
435
*/
431
436
public Builder chainClosing (PulsarTestContext otherContext ) {
432
- registerCloseable (otherContext );
437
+ otherContextToClose = otherContext ;
438
+ return this ;
439
+ }
440
+
441
+ /**
442
+ * Registers a closeable to close as the last one by prepending it to the closeables list.
443
+ */
444
+ public Builder prependCloseable (AutoCloseable closeable ) {
445
+ closeables .add (0 , closeable );
433
446
return this ;
434
447
}
435
448
@@ -584,9 +597,14 @@ public final PulsarTestContext build() {
584
597
try {
585
598
super .pulsarService .start ();
586
599
} catch (Exception e ) {
600
+ callCloseables (super .closeables );
601
+ super .closeables .clear ();
587
602
throw new RuntimeException (e );
588
603
}
589
604
}
605
+ if (otherContextToClose != null ) {
606
+ prependCloseable (otherContextToClose );
607
+ }
590
608
brokerService (super .pulsarService .getBrokerService ());
591
609
return super .build ();
592
610
}
0 commit comments