From 31336c2dce34044bca9781711a7dd60c36df7508 Mon Sep 17 00:00:00 2001 From: Andy Wilkinson Date: Thu, 25 Jun 2015 16:57:13 +0100 Subject: [PATCH] Allow matchers to be used to verify output captured by OutputCapture Closes gh-3330 --- .../boot/test/OutputCapture.java | 31 +++++++++++++++++-- 1 file changed, 29 insertions(+), 2 deletions(-) diff --git a/spring-boot/src/main/java/org/springframework/boot/test/OutputCapture.java b/spring-boot/src/main/java/org/springframework/boot/test/OutputCapture.java index 6cc5a81f03..37c53f5cc2 100644 --- a/spring-boot/src/main/java/org/springframework/boot/test/OutputCapture.java +++ b/spring-boot/src/main/java/org/springframework/boot/test/OutputCapture.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2014 the original author or authors. + * Copyright 2012-2015 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,17 +20,24 @@ import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import java.io.PrintStream; +import java.util.ArrayList; +import java.util.List; +import org.hamcrest.Matcher; import org.junit.rules.TestRule; import org.junit.runner.Description; import org.junit.runners.model.Statement; import org.springframework.boot.ansi.AnsiOutput; import org.springframework.boot.ansi.AnsiOutput.Enabled; +import static org.hamcrest.Matchers.allOf; +import static org.junit.Assert.assertThat; + /** * JUnit {@code @Rule} to capture output from System.out and System.err. * * @author Phillip Webb + * @author Andy Wilkinson */ public class OutputCapture implements TestRule { @@ -40,6 +47,8 @@ public class OutputCapture implements TestRule { private ByteArrayOutputStream copy; + private List> matchers = new ArrayList>(); + @Override public Statement apply(final Statement base, Description description) { return new Statement() { @@ -50,7 +59,15 @@ public class OutputCapture implements TestRule { base.evaluate(); } finally { - releaseOutput(); + try { + if (!OutputCapture.this.matchers.isEmpty()) { + String output = OutputCapture.this.toString(); + assertThat(output, allOf(OutputCapture.this.matchers)); + } + } + finally { + releaseOutput(); + } } } }; @@ -88,6 +105,16 @@ public class OutputCapture implements TestRule { return this.copy.toString(); } + /** + * Verify that the output is matched by the supplied {@code matcher}. Verification is + * performed after the test method has executed. + * + * @param matcher the matcher + */ + public void expect(Matcher matcher) { + this.matchers.add(matcher); + } + private static class CaptureOutputStream extends OutputStream { private final PrintStream original;