Mocking void methods in Groovy

2k Views Asked by At

I ran into a similar bug between Groovy 2.x and Mockito as this user did, where the Mockito.doNothing(...) method throws exceptions in Groovy for no apparent reason.

The accepted answer to that question explains what is happening:

The problem is Groovy is intercepting your method call before it reaches someVoidMethod. The method actually being called is getMetaClass which is not a void method.

I'm wondering: is there a "Groovier" way to mock void methods? Meaning, is there a way (a Groovy mocking lib, perhaps a technique involving closures or other dynamic constructs, etc.) to mock void methods with Groovy that would circumvent the problem in that identified question.

Please don't mark this as a dupe: if you notice, the accepted answer to that question just explained the root problem, but doesn't offer up any alternative, Groovy-friendly solution.


Example of mocking void method

Below, EntityValidator and WebResource are from third-party libs. Address is a class that is a part of my project.

@Test
void test() {
    given:
    EntityValidator mockValidator = Mockito.mock(EntityValidator)
    WebResource mockResource = Mockito.mock(WebResource)
    Address mockAddress = Mockito.mock(Address)
    Mockito.doNothing().when(mockValidator).validateId(1L)
    Mockito.when(mockResource.get(Address)).thenReturn(mockAddress)

    GetAddressCommandImpl fixture = new GetAddressCommandImpl(mockValidator, mockResource)
    fixture.id = 1L

    when:
    Address address = fixture.run()

    then:
    assert(address == mockAddress)
}
0

There are 0 best solutions below