我正在尝试在我的单元测试中测试异常的抛出。我试图对 delete 方法进行元分类,但它不想坚持。你能从代码中看出我做错了什么吗?
单元测试代码:
@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)
不会抛出我期望的异常。相反,它重定向到action: "list"
. 有谁知道如何覆盖 Product.delete() 方法以便我可以强制异常?