2015-10-05 50 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类,这开始失败。这让我回到了同样的问题 –