Grails Testing with Spock - Which Mocking Framework Select?

这一生的挚爱 提交于 2019-11-30 19:11:47

When you are using spock framework for testing, then try to leverage the options and styles provided by the framework itself.

Spock framework helps in achieving a BDD [Behavioral Design Development]. By behavior I meant, you can tightly couple the business acceptance scenario to the development cycle.

I tried to get your test case written in Spock as it can be re-written as:

@TestFor(MyController)
class MyControllerSpec extends ControllerSpec {

    void "test service method in called once and only once"(){
        //Defines the behavior of setup
        setup: "Only one invocation of service method" 
            def myService = Mock(MyService){
                //Make sure serviceMethod is called only once from the controller
                //Beauty of Spock is that you can test the cardinality of
                //method invocations.  
                1 * serviceMethod() >> "Hello"
            }
            controller.myService = myService

            //The above process can be followed 
            //for stubbing/mocking 'YourService' and 
            //then injecting it to controller like
            //controller.yourService = yourService

        //Defines the behavior of action
        when: "controller action is called" 
            controller.myAction()

        //Defines the behavior of expected results
        then: "Expect the stubbed service method output" 
            controller.response.contentAsString == "Hello"
    }
}

//Controller
def myAction() {
    render myService.serviceMethod()
}

If you see above, you define the behavior in each step. From an enterprise perspective, those behavior will be driven by BA or the stakeholders. By this way, you comply to ATDD/BDD(Acceptance Test Driven Dev/Behavior Test Driven Dev) and eventually a TDD(Test Driven Dev) for your project.

For more details on how to use spock framework effectively, visit spock framework docs.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!