Skip to content

Commit 94f80d1

Browse files
committed
Add proper unit tests for composite pattern
1 parent c837ffe commit 94f80d1

1 file changed

Lines changed: 90 additions & 0 deletions

File tree

Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
1+
package com.iluwatar.composite;
2+
3+
import org.junit.After;
4+
import org.junit.Before;
5+
import org.junit.Test;
6+
7+
import java.io.ByteArrayOutputStream;
8+
import java.io.PrintStream;
9+
10+
import static org.junit.Assert.assertEquals;
11+
import static org.junit.Assert.assertNotNull;
12+
13+
/**
14+
* Date: 12/11/15 - 8:12 PM
15+
*
16+
* @author Jeroen Meulemeester
17+
*/
18+
public class MessengerTest {
19+
20+
/**
21+
* The buffer used to capture every write to {@link System#out}
22+
*/
23+
private ByteArrayOutputStream stdOutBuffer = new ByteArrayOutputStream();
24+
25+
/**
26+
* Keep the original std-out so it can be restored after the test
27+
*/
28+
private final PrintStream realStdOut = System.out;
29+
30+
/**
31+
* Inject the mocked std-out {@link PrintStream} into the {@link System} class before each test
32+
*/
33+
@Before
34+
public void setUp() {
35+
this.stdOutBuffer = new ByteArrayOutputStream();
36+
System.setOut(new PrintStream(stdOutBuffer));
37+
}
38+
39+
/**
40+
* Removed the mocked std-out {@link PrintStream} again from the {@link System} class
41+
*/
42+
@After
43+
public void tearDown() {
44+
System.setOut(realStdOut);
45+
}
46+
47+
/**
48+
* Test the message from the orcs
49+
*/
50+
@Test
51+
public void testMessageFromOrcs() {
52+
final Messenger messenger = new Messenger();
53+
testMessage(
54+
messenger.messageFromOrcs(),
55+
"Where there is a whip there is a way."
56+
);
57+
}
58+
59+
/**
60+
* Test the message from the elves
61+
*/
62+
@Test
63+
public void testMessageFromElves() {
64+
final Messenger messenger = new Messenger();
65+
testMessage(
66+
messenger.messageFromElves(),
67+
"Much wind pours from your mouth."
68+
);
69+
}
70+
71+
/**
72+
* Test if the given composed message matches the expected message
73+
*
74+
* @param composedMessage The composed message, received from the messenger
75+
* @param message The expected message
76+
*/
77+
private void testMessage(final LetterComposite composedMessage, final String message) {
78+
// Test is the composed message has the correct number of words
79+
final String[] words = message.split(" ");
80+
assertNotNull(composedMessage);
81+
assertEquals(words.length, composedMessage.count());
82+
83+
// Print the message to the mocked stdOut ...
84+
composedMessage.print();
85+
86+
// ... and verify if the message matches with the expected one
87+
assertEquals(message, new String(this.stdOutBuffer.toByteArray()).trim());
88+
}
89+
90+
}

0 commit comments

Comments
 (0)