Grails 2单元测试中的Metaclass删除域方法

Mic*_*son 2 grails groovy unit-testing

我试图在我的单元测试中测试抛出异常.我尝试了删除方法的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')
}
Run Code Online (Sandbox Code Playgroud)

控制器动作代码:

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)
    }
}    
Run Code Online (Sandbox Code Playgroud)

当我运行测试时,productInstance.delete(flush: true)不会抛出我期待的异常.而是重定向到action: "list".有谁知道如何覆盖Product.delete()方法,所以我可以强制异常?

ata*_*lor 7

你是在delete没有任何争论的情况下嘲笑,但是你的控制器会调用delete(flush: true).试着delete(Map)像这样嘲笑:

Product.metaClass.delete = { Map params -> 
    throw new DataIntegrityViolationException("...")
}
Run Code Online (Sandbox Code Playgroud)