如何模拟控制器内的命令对象 [英] How to Mock Command Object that is inside Controller

查看:13
本文介绍了如何模拟控制器内的命令对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个控制器类,其中有一个命令对象.我有一个方法 find() 使用这个命令对象如下:

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

}

现在,我正在编写一个测试用例来测试控制器中的 find 方法.但是测试用例在

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

  if(!sc.hasErrors())

因为 sc 仍然是空".我不确定如何在测试用例中处理这个内部类命令对象.到目前为止,我编写的测试用例是:

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

我如何处理测试用例中的内部类Command Object.我嘲笑它吗?我尝试过使用 mockCommandObject(?),但不确定如何将内部类命令对象传递给它?

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?

推荐答案

可以使用 mockCommandObject

You can use mockCommandObject

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

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

这篇关于如何模拟控制器内的命令对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆