2017-08-02 52 views
1

我有一個Java類斯波克如何嘲笑同一類的方法爲Java類

class MyClass { 
    void methodA() { 
     //something 
    } 
    void methodB() { 
     //something else 
    } 
} 

我想單元測試,但了methodA了methodA要看的methodB。我已經通過spock文檔,但我無法找到如何處理這種情況。我該怎麼辦?

注意 我沒能找到這個,所以我的自我回答上這是允許as per stackoverlfow's self-answering policy計算器這個問題的答案。添加此注意是爲了避免讓那些不知道自我回答策略的人士感到困惑,因此不要刪除。這

回答

2

它在斯波克文檔實際上記錄,請參見partial mocks

// this is now the object under specification, not a collaborator 
def persister = Spy(MessagePersister) { 
    // stub a call on the same object 
    isPersistable(_) >> true 
} 

when: 
persister.receive("msg") 

then: 
// demand a call on the same object 
1 * persister.persist("msg") 
1

一種解決方案是做到以下幾點在你的測試

def "your spock test"() { 
     MyClass myClass = Mock(MyClass) 
     myClass.methodA() >> { 
      callRealMethod() 
     } 
     myClass.methodB() >> { 
      //your mocking logic 
     } 
    expect: 
     //whatever you want to do 
    } 

callRealMethod允許你調用實際執行時,你是通過斯波克嘲諷。

+0

@LeonardBrünings答案在你的場景中更合適! – rafaelim

2

這是一個沒有嘲笑,你重寫方法需要一種方式:

def "your spock test"() { 
    MyClass myClass = new MyClass() { 
     @Override 
     void methodB() { 
      // do something related to this test 
     }  
    } 

    expect: 
    //whatever you want to do 
    myClass.methodA() 
} 
1

我會重新考慮一下這個解決方案,因爲你在這裏做的是you are testing mock instead of a real object。我不會在這個課堂上嘲笑任何東西,我會把它作爲一個簡單單位。如果methodB代表不同的單位範圍,則methodA那麼這可能是重構此類並將methodB中封裝的職責提取到注入您正試圖測試的單獨類中的一個很好的起點。然後嘲笑這個注入類更有意義在我看來。但首先總是問問自己爲什麼要模擬,如果有更好的選擇(嘲笑應該是你最後的選擇值得考慮)。