2011-07-13 107 views
1

這是我的示例代碼如何在Groovy中模擬另一個對象內實例化的對象?

class CommandLine { 

    def ls() { 
     def cmd = "ls".execute() 
     if(cmd.waitFor() != 0) { 
      throw new Execution() 
     } 
     return cmd.text 
    } 
} 

cmd變量保存型java.lang.Process中的一個對象。我如何剔除waitFor()方法來測試拋出的異常?如果我不能,有什麼方法可以重寫這個方法來促進自動化測試?

一般來說,你如何模擬在另一個類中實例化的對象,或者如何構造代碼以允許測試?

+0

那麼,常見的技術是模擬'execute'函數返回嘲弄'java.lang.Process'而不是常規的。 – bezmax

回答

0

答案是使用Groovy mocks代替內置的Grails mocks。

import groovy.mock.interceptor.MockFor 

class TestClass { 

    def test() { 
     def mock = new MockFor(classToBeMocked) 

     mock.demand.methodToBeMocked(1..1) { -> /* code */ } 

     mock.use { 
      /* 
      All calls to objects of type classToBeMocked will be 
      intercepted within this block of code. 
      */ 
     } 
    } 
} 
1

我不熟悉使用Groovy,但如果有嘲諷的方法String#execute()與方法waitFor()返回不爲零的結果返回嘲笑Process的機會,它會做到這一點

東西喜歡的方式:

Process mockedProcess = MockingFramework.mock(Process.class); // MockingFramework can be Mockito 
MockingFramework.when(String.execute()).thenReturn(mockedProcess); 
MockingFramework.when(mockedProcess.waitFor).thenReturn(1); 

new CommandLine().ls(); // Boom! => Execution exception 
相關問題