Thursday, July 16, 2009

Scala and EasyMock

Writing tests is an integral part of coding. If you're writing unit tests without using a Mock library like EasyMock or jMock you better check one of them out.

Didn't test EasyMock to its extreme but until now I didn't see any problem. Using partial functions as follows looks like a nice pattern to use EasyMock. It takes care of the EZMock in the useMock utility method and creates a nice separation between the "expected" block and "executor" one:

  /**
* 1. gets a mockable class
* 2. creates a mock object out of it
* 3. executes the "expected" block
* 4. replays the mock
* 5. runs the execution code
* 6. verify the mock
*/
private def useMock[S](mockable : Class[S])(run : S => Unit)(expected : S => Unit ) {
val mock = createMock(mockable)
expected(mock)
replay(mock.asInstanceOf[Object])
run(mock)
verify(mock.asInstanceOf[Object])
}
Using it goes like this:
    val mockRunner = useMock (classOf[ToMock]) { mock =>
val toTest = new ToTest(mock)
toTest.doSomethingWithToMock()//should call method1() and method2() on mocked
} _
//change some conditions
mockRunner {mock =>
mocked.method1()
mocked.method2()
}

Creative Commons License This work by Eishay Smith is licensed under a Creative Commons Attribution 3.0 Unported License.