我最近将 Grails 1.3.7 项目升级到 Grails 2.0.4,并注意到我的许多带有模拟的单元测试已经开始失败。控制器测试似乎顺利通过,当您让服务相互协作并尝试模拟对协作者的调用时,问题就出现了。关于它的奇怪部分是,如果我运行单个测试,它会通过,但是一旦我运行整个套件,它们就会失败并给出错误:
No more calls to 'getName' expected at this point. End of demands.
junit.framework.AssertionFailedError: No more calls to 'getName' expected at this point. End of demands.
我什至尝试过使用 GMock 而不是 new MockFor(),但得到了这个非常相似的错误:
No more calls to 'getSimpleName' expected at this point. End of demands.
junit.framework.AssertionFailedError: No more calls to 'getSimpleName' expected at this point. End of demands.
这是一个人为的示例,展示了如何复制我得到的错误,以及 GitHub 上的整个示例项目https://github.com/punkisdead/FunWithMocks。关于如何完成这项工作的任何想法?
酒吧控制器:
package funwithmocks
class BarController {
def barService
def fooService
def index() { }
}
酒吧服务:
package funwithmocks
class BarService {
def fooService
def bazService
def serviceMethod() {
}
}
BarController测试:
package funwithmocks
import grails.test.mixin.*
import org.junit.*
import groovy.mock.interceptor.MockFor
/**
* See the API for {@link grails.test.mixin.web.ControllerUnitTestMixin} for usage instructions
*/
@TestFor(BarController)
class BarControllerTests {
def fooService
def barService
@Before
public void setUp() {
fooService = new MockFor(FooService)
fooService.use {
controller.fooService = new FooService()
}
barService = new MockFor(BarService)
barService.use {
controller.barService = new BarService()
}
}
@Test
void doSomething() {
controller.index()
}
}
BarServiceTests:包 funwithmocks
import grails.test.mixin.*
import org.junit.*
import groovy.mock.interceptor.MockFor
/**
* See the API for {@link grails.test.mixin.services.ServiceUnitTestMixin} for usage instructions
*/
@TestFor(BarService)
class BarServiceTests {
def fooService
def bazService
@Before
public void setUp() {
fooService = new MockFor(FooService)
fooService.use {
service.fooService = new FooService()
}
bazService = new MockFor(BazService)
bazService.use {
service.bazService = new BazService()
}
}
@Test
void callSomeService() {
service.serviceMethod()
}
}