Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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()

like image 538
Ritesh M Nayak Avatar asked Apr 18 '12 06:04

Ritesh M Nayak


People also ask

How do you mock a method in the same test class?

Mocking is done when you invoke methods of a class that has external communication like database calls or rest calls. Through mocking you can explicitly define the return value of methods without actually executing the steps of the method.

How do you mock a method call?

Mockito when() method It should be used when we want to mock to return specific values when particular methods are called. In simple terms, "When the XYZ() method is called, then return ABC." It is mostly used when there is some condition to execute.

What is the difference between mock and stub?

Mocks verify the behavior of the code you're testing, also known as the system under test. Mocks should be used when you want to test the order in which functions are called. Stubs verify the state of the system under test.

How do you mock a method in Spock?

In Spock, a Mock may behave the same as a Stub. So we can say to mocked objects that, for a given method call, it should return the given data. So generally, this line says: itemProvider. getItems will be called once with ['item-'id'] argument and return given array.


1 Answers

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.

like image 129
Ted Naleid Avatar answered Oct 17 '22 08:10

Ted Naleid