Skip to content

Instantly share code, notes, and snippets.

@meaganewaller
Created December 3, 2013 20:03
Show Gist options
  • Select an option

  • Save meaganewaller/7776518 to your computer and use it in GitHub Desktop.

Select an option

Save meaganewaller/7776518 to your computer and use it in GitHub Desktop.
java mocking paths
package com.mastermind;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.List;
public class CommandLineInterface {
PrintStream output = System.out;
public void setOutput(PrintStream output) {
this.output = output;
}
...
}
public class CommandLineInterfaceTest {
private CommandLineInterface cli = new CommandLineInterface();
..
@Test
public void itDisplaysAWelcomeMessage() {
MockOutputStream out = new MockOutputStream();
PrintStream printStream = new PrintStream(out);
cli.setOutput(printStream);
cli.displayWelcomeMessage();
assertEquals("", out.getStringHistory());
}
}
The MockOutputStream does work, it can mocks the output, when I remove line 8 from the CommandLineInterface test, the output is printed to the console. However, the assertion is failing with
Expected:
Actual : []
So, the StringHistory array isn't getting populated.
package com.mastermind;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
public class MockOutputStream extends OutputStream {
ArrayList<String> stringHistory = new ArrayList<String>();
@Override
public void write(int b) throws IOException {
}
public void write(String message) throws IOException {
stringHistory.add(message);
}
public ArrayList<String> getStringHistory() {
System.out.println("hi");
return stringHistory;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment