1 /******************************************************************************* 2 * Copyright (c) 2009, 2021 Mountainminds GmbH & Co. KG and Contributors 3 * This program and the accompanying materials are made available under 4 * the terms of the Eclipse Public License 2.0 which is available at 5 * http://www.eclipse.org/legal/epl-2.0 6 * 7 * SPDX-License-Identifier: EPL-2.0 8 * 9 * Contributors: 10 * Marc R. Hoffmann - initial API and implementation 11 * 12 *******************************************************************************/ 13 package org.jacoco.examples; 14 15 import static org.hamcrest.CoreMatchers.containsString; 16 import static org.hamcrest.MatcherAssert.assertThat; 17 import static org.hamcrest.core.Is.is; 18 import static org.junit.Assert.fail; 19 20 import java.io.ByteArrayOutputStream; 21 import java.io.PrintStream; 22 import java.io.UnsupportedEncodingException; 23 24 import org.hamcrest.Matcher; 25 import org.junit.rules.ExternalResource; 26 27 /** 28 * In-Memory buffer to assert console output. 29 */ 30 public class ConsoleOutput extends ExternalResource { 31 32 private final ByteArrayOutputStream buffer; 33 34 public final PrintStream stream; 35 ConsoleOutput()36 public ConsoleOutput() { 37 this.buffer = new ByteArrayOutputStream(); 38 try { 39 this.stream = new PrintStream(buffer, true, "UTF-8"); 40 } catch (UnsupportedEncodingException e) { 41 throw new AssertionError(e.getMessage()); 42 } 43 } 44 45 @Override after()46 protected void after() { 47 buffer.reset(); 48 } 49 containsLine(String line)50 public static Matcher<String> containsLine(String line) { 51 return containsString(String.format("%s%n", line)); 52 } 53 isEmpty()54 public static Matcher<String> isEmpty() { 55 return is(""); 56 } 57 getContents()58 public String getContents() { 59 try { 60 return new String(buffer.toByteArray(), "UTF-8"); 61 } catch (UnsupportedEncodingException e) { 62 fail(e.getMessage()); 63 return ""; 64 } 65 } 66 expect(Matcher<String> matcher)67 public void expect(Matcher<String> matcher) { 68 assertThat(getContents(), matcher); 69 } 70 71 } 72