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