Grails : How I do mock other methods of a class under test which might be called internally during testing

grailsgroovymockingtddtesting

I am writing a test for methodA() in a service class similar to the one given below.

Class SampleService {
  def methodA(){
     methodB()
  }

  def methodB(){
  }
}

When I test methodA(), I need to be able to mock the call to methodB() when testing methodA(). I am using version 2.0.x of grails. In the 1.3.x distributions, I would write a self mock like this

def sampleServiceMock = mockFor(SampleService) 
sampleServiceMock.demand.methodB { -> } 

But this doesn't work in the 2.0.x versions. I was wondering what are the other ways of mocking methodB() when testing methodA()

Best Answer

For this kind of problem I actually avoid mocks and use the built-in groovyProxy ability to cast a map of closures as a proxy object. This gives you an instance with some methods overridden, but others passed through to the real class:

class SampleService {
    def methodA() {
        methodB()
    }

    def methodB() {
        return "real method"
    }
}

def mock = [methodB: {-> return "mock!" }] as SampleService

assert "mock!" == mock.methodA()
assert "real method" == new SampleService().methodA()

I like that only changes an instance, can be done in a single line, and doesn't mess with the metaclass of anything outside of that instance that needs to be cleaned up.

Related Topic