unit-testing - 可以在 Controller 的show()方法中使用模拟域 “instance”吗?

标签 unit-testing grails mocking

我正在尝试将名为事件的模拟域实例传递给 Controller ​​的show()方法,但show()找不到相关事件,因此返回null。

请注意,以下代码段仍在进行中。

def "trying to show an event containing malicous code"() {
    given: "An event named with malicous code"
    mockDomain(Event)
    def event   = Mock(Event)
    event.title >> "<script type=\"text/javascript\">alert(\"XSS\");</script>"
    event.id    >> 1
    // Do I have to actually create a full-blown event considering all
    // constraints here?

    when: "I try to show that event"
    controller.params.id    = 1
    def result = controller.show()

    then: "The resulting title will be encoded HTML"
    result.eventInstance.title    == event.title.encodeAsHTML()
}

这是 Controller 的show()方法的开始:
def show = {
    def eventInstance = Event.get(params.id)

    // The event exists
    if (eventInstance) {
            // some processing here

            return [eventInstance: eventInstance, isSubscribed: sub ? true:false, sidebar: 'sidebar']
    }
  • 是否有一个简单的解决方案,或者我是否必须创建一个涵盖所有约束的成熟事件?
  • 如果我必须创建一个完整的事件,我将在哪里放置相应的方法? (目前,我们在BootStrap.groovy中使用的是 createEvent()方法进行初始设置,因此不必在此处重复执行该函数。)
  • 最佳答案

    尝试通过以下方式模拟Event对象:

    def event   = new Event()
    event.title = "<script type=\"text/javascript\">alert(\"XSS\");</script>"
    event.id    = 1 // optional 
    mockDomain Event, [event]
    

    除非您将event实例添加到mockDomain调用中,否则您将无法使用get检索它

    关于unit-testing - 可以在 Controller 的show()方法中使用模拟域 “instance”吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4690547/

    相关文章:

    docker - 尝试对 Grails 应用程序进行 docker 化时出错

    java - 使用 PowerMock 和 TestNG 模拟单个静态方法

    mocking - 模拟类 : methods hinting

    c# - 单元测试与集成测试 : Entity Framework Core In memory

    unit-testing - 测试驱动开发的缺点?

    class - Grails:将类文字存储在数据库中

    Grails:从 g:if 标签调用 taglib

    python - 检查 unittest.mock 调用参数不可知 w.r.t.它们是作为位置参数还是关键字参数传递

    visual-studio - 如何从 VS2012 单元测试中的代码覆盖率分析中排除名称以 ".Test"结尾的项目

    c# - 如何测试具有数据库查询来更新数据的方法?