Mocking Util class's static method using gmock

982 Views Asked by At
class SomeService{
  public String getValue(){
     return SomeUtil.generateValue();
  }
}

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

I want to unit test the SomeService.getValue method.

I am trying the following:

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

But it fails as the util method isn't actually getting mocked.

Question:

How can I unit test my service method?

1

There are 1 best solutions below

2
jalopaba On

I made a quick test and it is working without a hassle:

@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

If you need to invoke the service several times, you may need a stub, i.e.:

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