ObserverTest.java.

Uncle Bob's Agile Development Corner
OBSERVER—Evolving into a pattern, Part 2
by Robert C. Martin
Listing 7. ObserverTest.java.


import junit.framework.*;

public class ObserverTest extends TestCase
{
    private MockTimeSource source;
    private MockTimeSink sink;

    public ObserverTest(String name)
    {
        super(name);
    }

    public void setUp()
    {
        source = new MockTimeSource();
        sink = new  MockTimeSink(source);
        source.registerObserver(sink);
    }

    private void assertSinkEquals(
        MockTimeSink sink, int hours, int minutes, int seconds)
    {
        assertEquals(hours, sink.getHours());
        assertEquals(minutes, sink.getMinutes());
        assertEquals(seconds, sink.getSeconds());
    }

    public void testTimeChange()
    {
        source.setTime(3,4,5);
        assertSinkEquals(sink, 3,4,5);

        source.setTime(7,8,9);
        assertSinkEquals(sink, 7,8,9);
    }

    public void testMultipleSinks()
    {
        MockTimeSink sink2 = new MockTimeSink(source);
        source.registerObserver(sink2);

        source.setTime(12,13,14);
        assertSinkEquals(sink, 12,13,14);
        assertSinkEquals(sink2, 12,13,14);
    }
}

About the Author

Robert C. Martin is president of Object Mentor Inc., a firm that offers high-level, OO software design consulting, training, and development services. He is the author of Designing Object Oriented C++ Applications Using the Booch Method. He can be contacted at [email protected].