1 | package jpacman.model; |
2 | |
3 | import static org.junit.Assert.assertEquals; |
4 | import static org.junit.Assert.assertNotNull; |
5 | import static org.junit.Assert.assertTrue; |
6 | |
7 | import java.util.Observable; |
8 | |
9 | import org.junit.Before; |
10 | import org.junit.Test; |
11 | |
12 | /** |
13 | * Test that the observer update method |
14 | * is properly called upon changes. |
15 | * |
16 | * @author Arie van Deursen; Aug 5, 2003 |
17 | * @version $Id: ObserverTest.java,v 1.5 2008/02/08 12:30:19 arie Exp $ |
18 | */ |
19 | public class ObserverTest extends GameTestCase { |
20 | |
21 | /** |
22 | * The Engine acts as the subject in the observer pattern. |
23 | */ |
24 | private Engine theEngine; |
25 | |
26 | /** |
27 | * Attach the engine to a dedicated mock-observer counting observations. |
28 | */ |
29 | private MyObserver theObserver; |
30 | |
31 | /** |
32 | * Initialize engine and attach the observer to it, |
33 | * making use of superclass game. |
34 | */ |
35 | @Before public void setUp() { |
36 | assertNotNull(theGame); |
37 | theEngine = new Engine(theGame); |
38 | assertTrue(theEngine.inStartingState()); |
39 | theObserver = new MyObserver(); |
40 | theEngine.addObserver(theObserver); |
41 | } |
42 | |
43 | /** |
44 | * Simple observer which counts the number of events it sees. |
45 | */ |
46 | private class MyObserver implements java.util.Observer { |
47 | /** |
48 | * The update counter. |
49 | */ |
50 | private int nrOfUpdates = 0; |
51 | /** |
52 | * Make an observation, and update the counter. |
53 | * @param obs The observable (the engine); |
54 | * @param o remaining info, ignored. |
55 | */ |
56 | public void update(Observable obs, Object o) { |
57 | nrOfUpdates++; |
58 | } |
59 | } |
60 | |
61 | /** |
62 | * See if update events are triggered at all relevant |
63 | * places in the engine. |
64 | */ |
65 | @Test public void testUpdates() { |
66 | int expectedUpdates = 0; |
67 | assertEquals(expectedUpdates, theObserver.nrOfUpdates); |
68 | |
69 | theEngine.start(); |
70 | expectedUpdates++; |
71 | assertEquals(expectedUpdates, theObserver.nrOfUpdates); |
72 | assertTrue(theEngine.inPlayingState()); |
73 | |
74 | theEngine.movePlayer(1, 0); |
75 | expectedUpdates++; |
76 | assertTrue(theEngine.inPlayingState()); |
77 | assertEquals(expectedUpdates, theObserver.nrOfUpdates); |
78 | |
79 | theEngine.quit(); |
80 | expectedUpdates++; |
81 | assertTrue(theEngine.inHaltedState()); |
82 | assertEquals(expectedUpdates, theObserver.nrOfUpdates); |
83 | |
84 | theEngine.start(); |
85 | expectedUpdates++; |
86 | assertTrue(theEngine.inPlayingState()); |
87 | assertEquals(expectedUpdates, theObserver.nrOfUpdates); |
88 | |
89 | // todo: test updates for monster moves as well. |
90 | |
91 | } |
92 | } |