【发布时间】:2016-07-06 06:10:08
【问题描述】:
我有一个控制器方法,它在它内部创建一个域实例并保存它。我需要模拟此保存失败,因此我正在考虑模拟此域并且对于保存方法我抛出异常。有没有办法模拟捐助者类。
def method(){
...
Donor donor = new Donor()
donor.properties = convertedParams
donor.save(failOnError: true)
...
}
我知道如何模拟在控制器内部使用的服务
def mock = new groovy.mock.interceptor.MockFor(ExampleService)
def exampleService = controller.exampleService
mock.demand.exampleMethod(){ Long id, TransactionResponse tr ->
throw new RegistrationActivationException(new IllegalStateException('something went wrong'), [])
}
mock.use{
controller.exampleService = new ExampleService()
model = controller.exampleMethod()
}
因此,上面的代码将模拟出控制器中使用的 ExampleService 服务。有没有办法做这样的模拟,但不是针对服务,而是针对在上面第一个代码块中的方法内部实例化的域。我需要模拟出 Donor 类,当调用 save 时,我需要抛出异常以模拟和测试当捐助者保存失败时会发生什么。
感谢您的帮助!谢谢!
【问题讨论】:
-
你使用什么测试框架?
-
它看起来像一个单元测试域场景。因此,您可能会在 grails 文档docs.grails.org/latest/guide/single.html#unitTestingDomains 中找到有用的阅读单元测试域部分
-
好的,这就是答案。 stackoverflow.com/questions/38220338/…
标签: grails