Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,10 @@ void store(ApplicationContext applicationContext, String name, WireMockServer wi
resolve(applicationContext).put(name, wireMockServer);
}

void remove(ApplicationContext applicationContext) {
store.remove(applicationContext);
}

Collection<WireMockServer> findAllInstances(ExtensionContext extensionContext) {
return resolve(extensionContext).values();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -100,8 +100,11 @@ private void registerShutdownHooks(
final WireMockServer server) {
context.addApplicationListener(
event -> {
if (event instanceof ContextClosedEvent) {
if (event instanceof ContextClosedEvent closedEvent) {
this.stopWireMockServer(name, server);
if (closedEvent.getApplicationContext() == context) {
Store.INSTANCE.remove(context);
}
}
});

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
package org.wiremock.spring.internal;

import static org.assertj.core.api.Assertions.assertThat;

import java.lang.ref.WeakReference;
import org.junit.jupiter.api.Test;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.wiremock.spring.ConfigureWireMock;

class StoreContextLeakTest {

@ConfigureWireMock(name = "leak-test")
static class Configured {}

@Test
void closedContextCanBeGarbageCollected() throws InterruptedException {
WeakReference<AnnotationConfigApplicationContext> contextRef = startAndCloseContext();

for (int i = 0; i < 50 && contextRef.get() != null; i++) {
System.gc();
Thread.sleep(50);
}

assertThat(contextRef.get()).isNull();
}

private static WeakReference<AnnotationConfigApplicationContext> startAndCloseContext() {
ConfigureWireMock options = Configured.class.getAnnotation(ConfigureWireMock.class);
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
context.refresh();
new WireMockServerCreator(options.name()).createWireMockServer(context, options);
context.close();
return new WeakReference<>(context);
}
}