views:

422

answers:

2

I am new to unit testing and mocking. I am trying to unit test an abstract domain class in Grails. How should I mock an implementation so I can unit test the constraints of the domain class? Is there a way to use the mock libraries that come with groovy or grails? Should I just implement a class that simply extends the abstract class?

+5  A: 

One cool thing about groovy (among many) is that you can use a map of method names with closures as values to mock out a class. This includes abstract classes.

abstract class Foo {
    def foo() {
       return bar() + 1
    }    

    abstract int bar()
}

def fooInst = [bar: {-> return 1 }] as Foo
assert 2 == fooInst.foo()
Ted Naleid
Groovy ROCKS!!! I can't believe it is that easy. Thank you very much!
Matthew Sowders
What if the abstract class does not have the default constructor?
Dan
A: 

Yes, what if there is no default constructor? How easy is this?

na