我最近将Grails 1.3.7项目升级到Grails 2.0.4并注意到我的许多单元测试已经开始失败。 Controller测试似乎传递得很好,当您让服务彼此协作并尝试模拟对协作者的调用时,就会出现问题。关于它的一个奇怪的部分是,如果我运行单个测试,它会通过,但是一旦我运行整个套件,它们就会失败并给出错误:
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而不是新的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.
这是一个人为的例子,展示了如何在https://github.com/punkisdead/FunWithMocks复制我正在获得的错误以及GitHub上的整个示例项目。有关如何使这项工作的任何想法?
BarController:
package funwithmocks
class BarController {
def barService
def fooService
def index() { }
}
BarService:
package funwithmocks
class BarService {
def fooService
def bazService
def serviceMethod() {
}
}
BarControllerTests:
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()
}
}
答案 0 :(得分:1)
你不应该将新的测试mixin与MockFor
groovy类结合起来。使用MockFor
方法替换所有mockFor
实例。
http://grails.org/doc/latest/guide/testing.html#mockingCollaborators