Skip to content

Commit

Permalink
Use ExtensionContext.Store in OutputCaptureExtension
Browse files Browse the repository at this point in the history
This commit refactors OutputCaptureExtension so that state is stored in
the ExtensionContext.Store instead of in the extension.

This is more idiomatic for JUnit Jupiter extensions and allows for
potential concurrent use of the extension.
  • Loading branch information
sbrannen committed Jun 3, 2019
1 parent 9a2fe1d commit 490e315
Showing 1 changed file with 16 additions and 8 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@
import org.junit.jupiter.api.extension.BeforeEachCallback;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.api.extension.ExtensionContext;
import org.junit.jupiter.api.extension.ExtensionContext.Namespace;
import org.junit.jupiter.api.extension.ExtensionContext.Store;
import org.junit.jupiter.api.extension.ParameterContext;
import org.junit.jupiter.api.extension.ParameterResolutionException;
import org.junit.jupiter.api.extension.ParameterResolver;
Expand Down Expand Up @@ -66,30 +68,28 @@
public class OutputCaptureExtension implements BeforeAllCallback, AfterAllCallback,
BeforeEachCallback, AfterEachCallback, ParameterResolver {

private final OutputCapture outputCapture = new OutputCapture();

OutputCaptureExtension() {
// Package private to prevent users from directly creating an instance.
}

@Override
public void beforeAll(ExtensionContext context) throws Exception {
this.outputCapture.push();
getOutputCapture(context).push();
}

@Override
public void afterAll(ExtensionContext context) throws Exception {
this.outputCapture.pop();
getOutputCapture(context).pop();
}

@Override
public void beforeEach(ExtensionContext context) throws Exception {
this.outputCapture.push();
getOutputCapture(context).push();
}

@Override
public void afterEach(ExtensionContext context) throws Exception {
this.outputCapture.pop();
getOutputCapture(context).pop();
}

@Override
Expand All @@ -100,8 +100,16 @@ public boolean supportsParameter(ParameterContext parameterContext,

@Override
public Object resolveParameter(ParameterContext parameterContext,
ExtensionContext extensionContext) throws ParameterResolutionException {
return this.outputCapture;
ExtensionContext extensionContext) {
return getOutputCapture(extensionContext);
}

private OutputCapture getOutputCapture(ExtensionContext context) {
return getStore(context).getOrComputeIfAbsent(OutputCapture.class);
}

private Store getStore(ExtensionContext context) {
return context.getStore(Namespace.create(getClass()));
}

}

0 comments on commit 490e315

Please sign in to comment.