【问题标题】:How can I unit test a Grails controller when using a custom property editor?使用自定义属性编辑器时如何对 Grails 控制器进行单元测试?
【发布时间】:2011-11-27 20:04:40
【问题描述】:

我想使用这里描述的技术:Grails bind request parameters to enum 自动将枚举的字符串表示绑定到域实例。 该技术工作正常,但我现有的控制器单元测试失败,因为在单元测试期间未加载自定义编辑器。我不想仅仅为了这种数据绑定技术而为每个控制器切换到集成测试。

当您拥有自定义属性编辑器时,是否有办法unit 测试控制器操作?

【问题讨论】:

    标签: unit-testing grails propertyeditor


    【解决方案1】:

    据我所知,spring 应用程序上下文在单元测试中不可用,因此您的属性注册商和属性编辑器不会被注册。所以自定义属性编辑器在单元测试中不起作用。但是,grails 使用 GrailsDataBinder - 它是 DataBinder 的子类,您也许可以做一些元编程和元类的东西,以便在调用 bind() 时注册并找到您的自定义属性编辑器。

    【讨论】:

    • 在 grails 2.x 中,GrailsUnitTestMixin 可以在单元测试中使用 applicationContext。
    【解决方案2】:

    在 Grails 2.x 中,您可以在单元测试中定义额外的 bean,只需在设置中首先使用 defineBeans

    @TestFor(MyController)
    class MyControllerTests {
    
      @Before
      void setup() {
        defineBeans {
          myCustomEditorRegistrar(MyCustomEditorRegistrar)
        }
      }
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多