O'Reilly logo

JUnit Pocket Guide by Kent Beck

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Fixtures

One of the most time-consuming parts of writing tests is writing the code to set the world up in a known state and then return it to its original state when the test is complete. Here is a test of a server and client communicating:

public void testPing(  ) {
    Server s= new Server(  );
    s.start(  );
    Client c= new Client(  );
    c.start(  );
    c.send("ping");
    assertEquals("ack", c.receive(  ));
    c.stop(  );
    s.stop(  );
}

To implement this correctly, we have to wrap the stop( ) calls in a finally block so that if something goes wrong in sending or receiving, the client and server will still be stopped:

public void testPing(  ) {
    Server s= new Server(  );
    s.start(  );
    try {
        Client c= new Client(  );
        c.start(  );
        try {
            c.send("ping");
            assertEquals("ack", c.receive(  ));
        } finally {
            c.stop(  );
        }
    } finally {
        s.stop(  );
    }
}

The actual content of the test is lost in the noise of creating a predictable state of the world against which to test. And this example is much simpler than many of the situations you will encounter in real testing.

The problem gets even worse when you write several tests with a similar setup. Once we get "ping" working, we test to be sure that all the other messages gets the expected replies. Without some help from our testing framework we would have to duplicate the boilerplate for each test we write.

JUnit supports sharing the setup code. Before a test method is run, a template method called setUp( ) is invoked. setUp( ) is intended as the place where you create the objects against ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required