我创建了一个 BaseController 并将其混入其他 Controller 中。

例子:

class BaseController () {
  def somemethod () {
    return "some method"
  }
}

@Mixin(BaseController)

class MyController {
   def getsomething() {
     def test = somemethod()
     return test
   }
}

我正在尝试为 MyController 编写一个测试用例,但是它失败了,因为它找不到 somemethod

我的测试目前看起来像这样
@TestFor(MyController)
class MyControllerSpec extends Specification {
  def "test getsomething" () {
    when:
      def m = controller.getsomething()
    then:
      response.contentAsString == "some method"
  }
}

但我不断收到这样的错误:
No signature of method: somemethod() is applicable for argument types: () values: []

问题

如何为 MyController 编写 spock 测试,以便它也能找到 somemethod

最佳答案

@TestMixin(BaseController) 的 Spock 测试中使用 MyController 是否有效?
Ans:- 不,这不是必需的。

更新 MyController 中需要进行一些小的修改。使用 render 而不是 return 。这是详细信息:

class BaseController {
    def someMethod() {
        "Some Method"
    }
}

import grails.util.Mixin
//Remember to use Grails @Mixin instead of Groovy @Mixin
@Mixin(BaseController)
class MyController {
    def getSomething() {
        def test = someMethod()
        render test
    }
}

//Unit Test
@TestFor(MyController)
class MyControllerUnitSpec extends Specification {
    void "test get something"() {
        when:
            controller.getSomething()
        then:
            response.contentAsString == "Some Method"
    }
}

//Controller Integration Test
import grails.plugin.spock.ControllerSpec
class MyControllerIntSpec extends ControllerSpec {
    void "test get something integration"() {
        when:
            controller.getSomething()
        then:
            controller.response.contentAsString == "Some Method"
    }
}

注释:-
我在测试时发现了一些困难,如下所列:-
  • 上述测试通过了初始运行。但是,当我将 render 更改为 return 只是为了看到我的测试失败时,由于我在 @Mixin 中使用的 Grails MyController(withFormat 的两个版本),我遇到了编译错误。有时我觉得它玩得不好。将 mixin 更改为 Groovy @Mixin 一切顺利。我不喜欢那样。我不得不坚持使用 Grails @Mixin 。显然,令人惊讶的是,执行 grails clean && grails compile 根除了这个问题。我能够正确使用 Grails @Mixin。我仍在关注这种差异。
  • 如果上述问题一直存在,我会想到在单元测试的setup()方法中添加运行时mixin。

  • 喜欢
    def setup(){
        //I would not like to do the same in Integration test
        //Integration test should do it for me atleast.
        MyController.mixin BaseController
    }
    
  • 我在集成测试中使用了 ControllerSpec 而不是 IntegrationSpec。似乎在 Controller 的 ControllerSpec 中更好地维护了注入(inject)和约定。如果你看到了,我没有在 int 测试中实例化 MyContoller
  • 我没有在普通的 Junit 单元和集成测试中测试过它,它们也应该很好。
  • 10-07 13:15