Thursday, February 14, 2008

ScalaTest and Mocking

I've added in some mocking into ScalaTest thanks to specs integration. I've done it in a BDD style, kind of like rspec's given/when/then. rspec is much further along and I still need to learn a lot more about it, but thats okay. I'm hoping just to get some peoples opinions on readability and such. Here are a couple very quick examples.

mockTest( "Report should be generated for each invocation" ){

val reporter = mock(classOf[Reporter])

expecting( "reporter gets 10 passing reports because invocationCount=10" ) {
nTestsToPass( 10, reporter )

when ( "run the suite with method that has invocationCount=10" ){
new TestNGSuiteWithInvocationCount().runTestNG(reporter)

mockTest( "Reporter should be notified when test is skipped" ){

val reporter = mock(classOf[Reporter])

expecting ( "a single test should fail, followed by a single test being skipped" ){

when ( "run the suite with a test that should fail and a test that should be skipped" ){
new SuiteWithSkippedTest().runTestNG(reporter)

As you can see, I've added expecting and when blocks, which optionally take a String (that is currently just used for readability). The simple idea here is that I have grouped chunks of my test into places that make sense, hopefully making it easier for someone reading the test. Do you like it? Do you hate it? Any other opinions that could help?


  1. I like it. Would be fun to play around with a bit.
    Is the code available somewhere?

    Have you looked at the specify() {..} methods in ScalaTest trunk?


  2. Sorry I haven't gotten back to you sooner. The code is in trunk, but since its still experimental, we've left it in the test area. You can find it in app/tests/org/scalatest/jmock. I used it to write most of my tests for the Scalatest/TestNG integration, and you can find examples of that in app/tests/org/scalatest/testng.

    The path for the mocking stuff will most definitely change soon.

    As for the specify methods, I was somewhat familiar with them, but I'm not sure they exist anymore. Can you refresh my memory on them?