0

I have a Java method that looks something like this:

public Map<String <Set<Something>> mathod() {
  Map<String, Set<Something>> originalMap = createMap();
    
  return Utils.fixMap(originalMap);
}

I have a groovy/spock test and I need to test the method and I need to mock the Utils and make fixMap() return its input.

Originally, the Utils method was a service and it was mocked like this:

UtilService mock = Mock(UtilService) {
  fixMap(_ as Map) >> { Map input -> return input }
}

I can't figure out how to do it. Please help, thanks in advance.

  • If you mock the Utility function you do not test anything, so the test makes no sence – Jens Jan 23 '23 at 13:15
  • I have a simplified version of the code here, it makes sense for my case, I just need answer for the specific question: how to get the input as output on a mocked static method call – Paris Karagiannopoulos Jan 23 '23 at 13:18
  • Maybe [this](https://stackoverflow.com/questions/15824315/mock-static-method-with-groovymock-or-similar-in-spock) helps – Jens Jan 23 '23 at 13:20
  • Doesn't explain how the static method returns its own input as response – Paris Karagiannopoulos Jan 23 '23 at 14:22
  • You cannot mock static Java (or any non-Groovy) methods with Spock out of the box. So either refactor your code to no longer use static utility classes - you already noticed how difficult it is to test them - or you wrap them in non-static facade classes. The least attractive option is to add Mockito, Sarek or another mocking tool of your choice, which is capable of mocking static methods. – kriegaex Jan 24 '23 at 11:33

1 Answers1

1

Unless your code is in Groovy, which it apparently isn't, there is not way to do this with Spock's built-in mocking.

However, you could use Mockito to do the static mocking.

In general, I advise against doing anything of the sort, as it normally points to issues with the implementation. Consider refactoring your code, so that Utils.fixMap actually gets injected, which in turn can then be mocked easily.

Leonard Brünings
  • 12,408
  • 1
  • 46
  • 66