2
我想在我的單元測試中測試異常拋出。我試圖對刪除方法進行元類化,但它不想堅持。你能從代碼中發現我做錯了什麼嗎?Grails 2單元測試中的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()方法,所以我可以強制異常?
你是對的。我以前曾經使用過attrs,就像'delete = {attrs - > ...}',但我沒想過要使用像Map這樣的特定類型。謝謝,這真的開始困擾我。 –