【问题标题】:Grails integration test mock not cleanedGrails 集成测试模拟未清理
【发布时间】:2016-02-26 08:11:31
【问题描述】:

我无法解决两个 spock 集成测试之间的奇怪污染情况。我想我做错了什么,但我不明白是什么。

这两个集成测试是测试同一个控制器的不同情况。在第一个中我模拟了一个服务,而在第二个中我不模拟。

以下是两个测试的重要部分:

测试 1:

// CodeControllerSpec.groovy
...
def controller = new CodeController()
def serviceMock = new MockFor(PollutingService)
serviceMock.demand.search(1) { a, b, c ->
    return [id: 1]
}
controller.myService.pollutingService = serviceMock.proxyInstance()
controller.save()
...
then: 
serviceMock.verify(controller.myService.pollutingService)

测试 2:

// CodeEngineSpec.groovy
...
def controller = new CodeController()
controller.show()
...
then: 
...

控制器和服务如下

// CodeController
class CodeController extends RestfulController<Code> {
    def myService

    def show() {
        ...
        myService.execute()
        ...
    }
}

// MyService
class MyService {

    def pollutingService

    def execute() {
        ...
        pollutingService.search(a, b, c)
        ...
    }
}

// PollutingService
class PollutingService {

    def search(a, b, c) {
        ...
        ...
    }
}

如果我一个接一个地运行这两个测试,它们都会通过,但是如果我一起运行它们,第二个会失败

No more calls to 'search' expected at this point. End of demands.

我确定使用了第一个服务中的模拟(我已经逐行调试了代码),但我不知道为什么在测试后没有清理模拟。 任何建议都非常欢迎。

我正在使用 grails 2.3.8

【问题讨论】:

    标签: grails


    【解决方案1】:

    首先,在集成测试中使用 mock 会产生不可预知的结果。

    但抛开这些不谈,您的第一个测试中的controller.myService 在哪里被实例化?我原以为调用controller = new CodeController() 会绕过controller.myService 的自动装配。

    【讨论】:

    • using mocks in integration tests has unpredictable results. 是什么意思?我确信服务在集成测试中是自动装配的,我会尝试实例化服务
    • 无论如何,请注意如果两个测试中的controller.myService是同一个对象,那么controller.myService.pollutingService在两个测试中也将是同一个对象。
    • 在接下来的几天里,我会写一些新的测试来验证你的建议。同时你能详细说明一下using mocks in integration tests has unpredictable results.的声明吗?谢谢
    • 比在集成测试中使用 mock 更成问题的是在集成测试中使用单元测试 Mixins 和注释(如 @TestFor),因为它们在幕后搞砸了元类。集成测试中的模拟问题较少,但您必须跟踪自己在做什么并自行清理。
    • 感谢您的帮助,解决方案是在集成测试结束时清理服务
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-08
    • 2012-04-25
    • 1970-01-01
    • 2016-04-13
    • 2023-03-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多