Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grails mockFor and How Best To Test The Method Is Called with Correct Arguments

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

My current plan is to use mockFor and then through the closure check the value passed in. Is there a better way to do the test through mockFor or the mocked object similar to what I can do with mockito to perform this same method call argument value test?

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

Thanks!

like image 925
finneycanhelp Avatar asked Mar 06 '11 14:03

finneycanhelp


1 Answers

I rarely use mockFor as I find groovy's built in metaClass stuff and as ClassName to be easier to work with and more powerful, I'd do this:

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

    controller.someAction()
    assertEquals "specific value", givenSomeItem
}
like image 179
Ted Naleid Avatar answered Oct 07 '22 21:10

Ted Naleid