How to mock Java methods with UUID params

Viewed 53

I'm mocking the response of a method using the Spock wildcard. Spock however does not recognise the wildcard, and treats the method as unmocked.

The method is from a Java class, and has a UUID parameter. I can't seem to match _ to that parameter when mocking.

Scenario 1 when using String param: (This works: mocked method returns "mocked foo")

class Foo{
    public String method() {
        String response = dependency.getText("some text")
        return response; //prints "foo"
    }
}

Spock test mocking for scenario 1:

@SpringBean
private Dependency dependencyMock  = Mock()

dependencyMock.getText(_) >> "mocked foo" //mocked foo is returned as expected

Scenario 2 when using UUID param: (method not mocked - mocked method still returns "foo")

class Foo{
    public String method() {
        String response = dependency.getText(UUID.randomUuid())
        return response; //prints "foo"
    }
}

Spock test mocking for scenario 2:

@SpringBean
private Dependency dependencyMock  = Mock()

dependencyMock.getText(_) >> "mocked foo" //foo is still returned

I've tried using PowerMock to mock the final UUID class but Sputnik runner is not supported for later versions of Spock.

Spock version: 2.2-groovy-3.0

1 Answers

After a lot of hair pulling, I found that UUID can only be mocked using the interactions mock: where you count the invocations of a method while also mocking its response at the same time in the then clause. I dont know why this is the case for UUID, and not for other classes like String or primitive types like int.

Code which doesn't mock:

given:
dependencyMock.getText(_) >> "mocked foo"  // returns "foo"

when:

then:

Code which mocks:

given:

when:

then:
1 * dependencyMock.getText(_) >> "mocked foo" //returns "mocked foo"
Related