Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/unit-testing/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Unit testing Grails2单元测试中的元类删除域方法_Unit Testing_Grails_Groovy - Fatal编程技术网

Unit testing Grails2单元测试中的元类删除域方法

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

我试图在单元测试中测试异常的抛出。我试图对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)
不会引发我预期的异常。相反,它重定向到
操作:“列表”
。有人知道如何重写Product.delete()方法以便我可以强制执行异常吗

您正在模拟
delete
而没有任何参数,但是您的控制器调用
delete(flush:true)
。尝试模仿
delete(Map)
如下:

Product.metaClass.delete = { Map params -> 
    throw new DataIntegrityViolationException("...")
}

你完全正确。我以前使用过一个attrs,比如so
delete={attrs->…}
,但我没有想到使用像Map这样的特定类型。谢谢你,这真的开始困扰我了。