More Mandatory Mocking


package net.unicon;

import java.sql.*;

class ThingTest3 extends GroovyTestCase { 

  void testTestMe() {
    int score = 42;  //what we expect to get back
    int erId = -42;  //an argument to pass
    int rowcount = 0;  //state for the result set mock

    def rs = [  next : { -> rowcount++ == 0 },  //rowcount has lexical scope
                getInt : { assertEquals(1, rowcount);  //only called once
                           pos -> assertEquals(1, pos); 
                           return score; },
	       close : { -> }                  //simplest possible closure
             ] as ResultSet;

    def stmt = [ executeQuery : { -> return rs; },
                 setInt : { pos, id -> 
                            assertEquals(1, pos); 
	                    assertEquals(erId, id);
	                  },
	         close : { -> } 
               ] as PreparedStatement;


    def conn = [ prepareStatement :  { q->  
                  assertEquals(Thing3.query, q); //WHOA!!
	          return stmt;  //can't resist "return"
    }] as Connection;

    def thing = new Thing3();
    assertEquals(score, thing.testMe(conn, erId));
  }
}

Prev Next