How to Mock Command Object that is inside Controll

2019-02-15 19:18发布

问题:

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