2015-10-05 53 views
0
class SomeService{ 
    public String getValue(){ 
    return SomeUtil.generateValue(); 
    } 
} 

class SomeUtil{ 
    public static String generateValue() { 
     return "yahoo"; 
    } 
} 

我想單元測試​​方法。嘲笑Util類使用gmock的靜態方法

我嘗試以下操作:

@Test 
void "getValue should return whatever util gives"(){ 
    def mockSomeUtil = mock(SomeUtil) 
    mockSomeUtil.static.generateValue().returns("blah") 
    play { 
     Assert.assertEquals(someService.getValue(), "blah") 
    } 
} 

但隨着util的方法實際上並沒有得到嘲笑失敗。

問題

我單位如何測試我的服務的方法?

+0

你擴展GMockTestCase? – jalopaba

+0

我正在使用@WithGMock註釋 –

回答

0

我做了一個快速測試,它是工作不麻煩:

@Grapes([ 
    @Grab(group='org.gmock', module='gmock', version='0.8.3'), 
    @Grab(group='junit', module='junit', version='4.12') 
]) 

import org.gmock.* 
import org.junit.* 
import org.junit.runner.* 

class SomeService { 
    public String getValue(){ 
     return SomeUtil.generateValue() 
    } 
} 

class SomeUtil { 
    public static String generateValue() { 
     return "yahoo" 
    } 
} 

@WithGMock 
class DemoTest { 
    def someService = new SomeService() 

    @Test 
    void "getValue should return whatever util gives"() { 
     def mockSomeUtil = mock(SomeUtil) 
     mockSomeUtil.static.generateValue().returns("blah") 

     play { 
      Assert.assertEquals(someService.getValue(), "blah") 
     } 
    } 
} 

def result = JUnitCore.runClasses(DemoTest.class) 
assert result.failures.size() == 0 

如果需要調用服務幾次,你可能需要一個stub,即:

mockSomeUtil.static.generateValue().returns("blah").stub() 
+0

我看到的唯一區別是,我正在使用TestNG運行它,但我不認爲它應該有所作爲 –

+0

好的...因此,只要我在單獨的文件中提取服務和util類,這開始失敗。這讓我回到了同樣的問題 –