1+ package com .iluwatar .strategy ;
2+
3+ import org .junit .After ;
4+ import org .junit .Before ;
5+ import org .junit .Test ;
6+ import org .junit .runner .RunWith ;
7+ import org .junit .runners .Parameterized ;
8+
9+ import java .io .PrintStream ;
10+ import java .util .Arrays ;
11+ import java .util .Collection ;
12+
13+ import static org .mockito .Mockito .mock ;
14+ import static org .mockito .Mockito .verify ;
15+ import static org .mockito .Mockito .verifyNoMoreInteractions ;
16+
17+ /**
18+ * Date: 12/29/15 - 10:58 PM
19+ *
20+ * @author Jeroen Meulemeester
21+ */
22+ @ RunWith (Parameterized .class )
23+ public class DragonSlayingStrategyTest {
24+
25+ /**
26+ * @return The test parameters for each cycle
27+ */
28+ @ Parameterized .Parameters
29+ public static Collection <Object []> data () {
30+ return Arrays .asList (
31+ new Object []{
32+ new MeleeStrategy (),
33+ "With your Excalibur you severe the dragon's head!"
34+ },
35+ new Object []{
36+ new ProjectileStrategy (),
37+ "You shoot the dragon with the magical crossbow and it falls dead on the ground!"
38+ },
39+ new Object []{
40+ new SpellStrategy (),
41+ "You cast the spell of disintegration and the dragon vaporizes in a pile of dust!"
42+ }
43+ );
44+ }
45+
46+ /**
47+ * The tested strategy
48+ */
49+ private final DragonSlayingStrategy strategy ;
50+
51+ /**
52+ * The expected action on the std-out
53+ */
54+ private final String expectedResult ;
55+
56+ /**
57+ * The mocked standard out {@link PrintStream}, required since some actions don't have any
58+ * influence on accessible objects, except for writing to std-out using {@link System#out}
59+ */
60+ private final PrintStream stdOutMock = mock (PrintStream .class );
61+
62+ /**
63+ * Keep the original std-out so it can be restored after the test
64+ */
65+ private final PrintStream stdOutOrig = System .out ;
66+
67+ /**
68+ * Create a new test instance for the given strategy
69+ *
70+ * @param strategy The tested strategy
71+ * @param expectedResult The expected result
72+ */
73+ public DragonSlayingStrategyTest (final DragonSlayingStrategy strategy , final String expectedResult ) {
74+ this .strategy = strategy ;
75+ this .expectedResult = expectedResult ;
76+ }
77+
78+ /**
79+ * Inject the mocked std-out {@link PrintStream} into the {@link System} class before each test
80+ */
81+ @ Before
82+ public void setUp () {
83+ System .setOut (this .stdOutMock );
84+ }
85+
86+ /**
87+ * Removed the mocked std-out {@link PrintStream} again from the {@link System} class
88+ */
89+ @ After
90+ public void tearDown () {
91+ System .setOut (this .stdOutOrig );
92+ }
93+
94+ /**
95+ * Test if executing the strategy gives the correct response
96+ */
97+ @ Test
98+ public void testExecute () {
99+ this .strategy .execute ();
100+ verify (this .stdOutMock ).println (this .expectedResult );
101+ verifyNoMoreInteractions (this .stdOutMock );
102+ }
103+
104+ }
0 commit comments