How to Mock Command Object that is inside Controller

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

问题


I have a controller class, inside of which i have a command object. I have a method find() which uses this command object as follows:

class itemController{

    //command object
    class SearchCommand{
        String email
        static constraints={
            email blank:false,email:true
        }

def find = {SearchCommand sc ->
    if(!sc.hasErrors()){
     ----- do something---
}

}

Now, I am writing a test case to test the find method in the controller. But the test case fails at

  if(!sc.hasErrors())

as sc is still 'null'. I am not sure how to handle this inner class command object in the test case. The test case that i have written so far is:

class itemControllerTests extends ControllerUnitTestCase {

    void testFind(){
    def model = controller.find()
    assertNotNull(model)
    }
}

How do I handle the inner class Command Object in the test case. Do I mock it? I have tried using mockCommandObject(?), but not sure how should i pass the inner class command object to this?


回答1:


You can use mockCommandObject

Class RioController

class RioController {
    class UserCommand{
        String email
        static constraints = {
            email blank: false, email: true
        }
    }

    def load={UserCommand cmd -> 
        if(cmd.validate()){
            flash.message = "Ok"
        }
        else{
            flash.message = "Where is the email?"
        }
    }
}

Class RioControllerTests

import grails.test.mixin.*
import org.junit.*

@TestFor(RioController)
class RioControllerTests {

    @Test
    void testLoad(){
        mockCommandObject RioController.UserCommand
        controller.load()
        assert flash.message == "Where is the email?"

        params.email = "verynew@email.com"
        controller.load()
        assert flash.message == "Ok"
    }
}


来源:https://stackoverflow.com/questions/12112415/how-to-mock-command-object-that-is-inside-controller

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