1
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?

jalopaba
  • 8,039
  • 2
  • 44
  • 57
Ankit Gupta
  • 275
  • 3
  • 12

1 Answers1

0

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()
jalopaba
  • 8,039
  • 2
  • 44
  • 57
  • The only difference I see is that I am running it with TestNG but I dont think it should make any difference – Ankit Gupta Oct 06 '15 at 10:39
  • Ok...So as soon as I extract the service and util classes in separate files, this starts failing. That brings me back to the same question – Ankit Gupta Oct 06 '15 at 11:10