我正在尝试在单元测试中测试抛出异常。我尝试了删除方法的metaclass,但它不想坚持。你能从代码中看出我做错了吗?
单元测试代码:
@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()方法,所以我可以强制异常?
答案 0 :(得分:7)
您在没有任何参数的情况下嘲笑delete
,但您的控制器会调用delete(flush: true)
。试着像这样嘲笑delete(Map)
:
Product.metaClass.delete = { Map params ->
throw new DataIntegrityViolationException("...")
}