I am Paul Wilson; Mere Complexities Limited, sells my consulting, coaching, and coding services. I am passionate about Agile, particularly Test Driven Development.


Testing class invariants

One way of looking at unit tests is in terms of Design by Contract: most tests define postconditions and there can also be value in having tests showing that a class fails-fast on precondition failure. While helping out on a TDD course this week it occurred to me that Junit 4 provides a simple mechanism for checking class invariants in unit tests: it’s particularly useful to be confident invariants hold even after exceptions have been thrown.

For example, a game of Blackjack may allow dealing only once.

 
 
    @After
    public void ensureInvariants() 
    {
        assertTrue(game.canDeal() == !game.isDealt()); 
    }
   

Of course, it wouldn’t be rocket science to do the same in Junit 3.8:


    protected void runTest() throws Throwable
    {
        super.runTest();  
        ensureInvariants();
    }

    public void ensureInvariants()
    {
        assertTrue(game.canDeal() == !game.isDealt());
    }

(PS credit to Malcolm Sparks for suggesting that I blog this.)


0 Comments:

Post a Comment

<< Home

subscribe here subscribe

About me

picture

Conference

RailsConf Europe 2008
Scotland on Rails Organiser

Previous blog posts

Blog archive

Other links: