2016-07-07 61 views
2

我有一個簡單的域MissingMethodException:使用groovy元類替換方法後沒有方法錯誤的簽名?

class Cat { 

    String name 

    static constraints = { 
    } 
} 

控制器如下:

class CatController { 

    def index() { } 


    def say(){ 


     def cat = new Cat(name: "cc") 
     cat.save() 

     render "done" 

    } 
} 

和我有一個測試的集成測試如下:

class CatTests extends GroovyTestCase{ 

    CatController controller = new CatController() 

    @Test 
    void testSomething() { 


     Cat.metaClass.save = { 

      throw new Exception("Asdasd") 
     } 

     shouldFail(Exception){ 

       controller.say() 

     } 


     GroovySystem.metaClassRegistry.removeMetaClass(Cat.class) 


    } 


    @Test 
    void testSomething2() { 

     def before_cat_count = Cat.count() 

     controller.say() 

     def after_cat_count = Cat.count() 

     assertEquals after_cat_count - before_cat_count, 1 


    } 


} 

我收到以下錯誤,當運行測試。現在

Failure: testSomething2(cat.CatTests) 
| groovy.lang.MissingMethodException: No signature of method: cat.Cat.count() is applicable for argument types:() values: [] 
Possible solutions: count(), ident(), print(java.lang.Object), print(java.io.PrintWriter), getCount(), wait() 
    at cat.CatTests.testSomething2(CatTests.groovy:37) 
| Completed 2 integration tests, 1 failed in 192ms 

,我懷疑,問題是,爲什麼它沒有找到這條線

def before_cat_count = Cat.count() 
testSomething2()方法的

計數方法。

我已經在方法testSomething的末尾刪除了元類。所以,我想知道爲什麼沒有找到count()方法。我感謝任何幫助!謝謝!

回答

0

也許根本

GroovySystem.metaClassRegistry.removeMetaClass(CAT)

根本貓,不Cat.class

從web源,我使用了一種用於這種類型的清理。

def revokeMetaClassChanges(Class type, def instance = null) { 
    GroovySystem.metaClassRegistry.removeMetaClass(type) 
    if(instance) { 
     instance.metaClass = null 
    } 
} 

有了這樣調用:很成功

cleanup: 
    revokeMetaClassChanges(FirstService, firstServiceInstance) 
    revokeMetaClassChanges(SecondService, null) 

+0

對不起,我只是用Cat而不是Cat.class作爲removeMetaClass參數,但那不起作用。 – kofhearts

+0

在Groovy中,可以使用類名替代靜態.class引用。也就是說,Cat和Cat.class是等價的。 – Corrodias

相關問題