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()
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With