【问题标题】:Mocking Util class's static method using gmock使用 gmock 模拟 Util 类的静态方法
【发布时间】:2016-01-02 04:42:40
【问题描述】:
class SomeService{
  public String getValue(){
     return SomeUtil.generateValue();
  }
}

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

我想对SomeService.getValue 方法进行单元测试。

我正在尝试以下方法:

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

但它失败了,因为 util 方法实际上并没有被嘲笑。

问题

如何对我的服务方法进行单元测试?

【问题讨论】:

  • 你在扩展 GMockTestCase 吗?
  • 我正在使用@WithGMock 注释

标签: java unit-testing groovy gmock


【解决方案1】:

我做了一个快速测试,它运行起来很轻松:

@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()

【讨论】:

  • 我看到的唯一区别是我使用 TestNG 运行它,但我认为它应该没有任何区别
  • 好的...所以一旦我将服务和实用程序类提取到单独的文件中,这就会开始失败。这让我回到同一个问题
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多