Grails mockFor and how best to test the method is called with the correct arguments

I want to verify that the controller calls the service method with the correct arguments. What is the best way to do this?

My current plan is to use mockFor, and then through closure check the passed value. Is there a better way to run a test via mockFor or a mocking object similar to what I can do with mockito to execute the same method test the value of an argument?

class HappyControllerTests extends ControllerUnitTestCase {
       :
    void testSomeValue() {
        def mockControl = mockFor(HappyService)
        def givenSomeItem = null
        mockControl.demand.serviceMethod(1..99) { String someItem -> givenSomeItem = someItem; }
        controller.happyService = mockControl.createMock() 

        controller.someAction()

        mockControl.verify()
        assertEquals("specific value", givenSomeItem)
    }
}

Thank!

+5
source share
1 answer

mockFor, groovy metaClass as ClassName, , :

void testSomeValue() {
    def givenSomeItem = null
    controller.happyService = [
        serviceMethod: { String someItem -> givenSomeItem = someItem }
    ] as HappyService

    controller.someAction()
    assertEquals "specific value", givenSomeItem
}
+13

All Articles