unit-testing - 在grails中执行 Controller 的单元测试时,不能使用grailsApplication.getMetadata.get (“”)

标签 unit-testing grails junit4 grails-controller

在我的grails应用程序中,在 Controller 中,我使用以下方法:

class SampleController {
   def action1 = {
     def abc = grailsApplication.getMetadata().get("xyz")
     render abc.toString()
   }
}

在运行应用程序时,它可以从application.properties中正确读取属性“xyz”,并且可以正常工作。但是当我为上述 Controller 编写单元测试用例时,如下所示:
class SampleControllerTests extends ControllerUnitTestCase {
  SampleController controller

  protected void setUp() {
    super.setUp()
    controller = new SampleController()
    mockController(SampleController)
    mockLogging(SampleController)
  }

  void testAction1() {
    controller.action1()
    assertEquals "abc", controller.response.contentAsString
  }
}

但是,当我执行“grails test-app”操作时,我希望它会从application.properties中拾取属性“xyz”,并将按预期返回。但它给出错误为“无此类属性:grailsApplication”。

我了解,我想我需要模拟grailsApplication对象,我也尝试了许多选项,但是所有这些都不起作用。

我是Grails的新手。

最佳答案

mockController不会模拟GrailsApplication,您需要自己做。

最快的解决方案是:

protected void setUp() {
        super.setUp()
        mockLogging(DummyController)
        GrailsApplication grailsApplication = new DefaultGrailsApplication()
        controller.metaClass.getGrailsApplication = { -> grailsApplication }
    }

该解决方案并不完美-它将在每次设置过程中创建一个新的DefaultGrailsApplication,并且mockController还会创建一些其他DefaultGrailsApplication实例。

请注意,您不需要自己调用mockController,这将由ControllerUnitTestCase为您完成。

关于unit-testing - 在grails中执行 Controller 的单元测试时,不能使用grailsApplication.getMetadata.get (“”),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15499558/

相关文章:

java - 在测试环境中实例化 context.xml 的位置

grails 2.3 具有动态表单的一对多数据绑定(bind)

.net - 如何在 NUnit 单元测试中记录错误和消息?

grails - GORM返回值查询组成

grails - 域使用addTo Map导致错误

java - JUnit4 使用测试套件运行特定包中的所有测试

junit - "Assert in junit.framework has been deprecated"- 接下来要使用什么?

java - Resources$NotFoundException 调用 Robolectric.buildActivity() 时

unit-testing - 实现一个假的 NHibernate 存储库

c# - Rhino mock 原始方法调用已过时