Unit testing Grails2单元测试中的元类删除域方法
我试图在单元测试中测试异常的抛出。我试图对delete方法进行元类化,但它不想继续。你能从代码中看出我做错了什么吗 单元测试代码:Unit testing Grails2单元测试中的元类删除域方法,unit-testing,grails,groovy,Unit Testing,Grails,Groovy,我试图在单元测试中测试异常的抛出。我试图对delete方法进行元类化,但它不想继续。你能从代码中看出我做错了什么吗 单元测试代码: @TestFor(ProductController) @TestMixin(DomainClassUnitTestMixin) class ProductControllerTests { void testDeleteWithException() { mockDomain(Product, [[id: 1, name: "Test Pro
@TestFor(ProductController)
@TestMixin(DomainClassUnitTestMixin)
class ProductControllerTests {
void testDeleteWithException() {
mockDomain(Product, [[id: 1, name: "Test Product"]])
Product.metaClass.delete = {-> throw new DataIntegrityViolationException("I'm an exception")}
controller.delete(1)
assertEquals(view, '/show/edit')
}
控制器操作代码:
def delete(Long id) {
def productInstance = Product.get(id)
if (!productInstance) {
flash.message = message(code: 'default.not.found.message', args: [message(code: 'product.label', default: 'Product'), id])
redirect(action: "list")
return
}
try {
productInstance.delete(flush: true)
flash.message = message(code: 'default.deleted.message', args: [message(code: 'product.label', default: 'Product'), id])
redirect(action: "list")
}
catch (DataIntegrityViolationException e) {
flash.message = message(code: 'default.not.deleted.message', args: [message(code: 'product.label', default: 'Product'), id])
redirect(action: "show", id: id)
}
}
运行测试时,
productInstance.delete(flush:true)
不会引发我预期的异常。相反,它重定向到操作:“列表”
。有人知道如何重写Product.delete()方法以便我可以强制执行异常吗 您正在模拟delete
而没有任何参数,但是您的控制器调用delete(flush:true)
。尝试模仿delete(Map)
如下:
Product.metaClass.delete = { Map params ->
throw new DataIntegrityViolationException("...")
}
你完全正确。我以前使用过一个attrs,比如so
delete={attrs->…}
,但我没有想到使用像Map这样的特定类型。谢谢你,这真的开始困扰我了。