4

I have a java class which i test in groovy/spock. The java class has a final field:

private static final log = Logger.getLogger(...)

I want to test if a method uses this logger, preferably using a mock. The problem is that this field is final so I can't just set it. I know that there are workarounds like:

modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);

but these are awful hacks. Is there a more groovy way to do this?

Wojciech Górski
  • 945
  • 11
  • 29

1 Answers1

-1

You could try testing logging by configuring your logger instead of mocking it.

Perhaps, configure your logger to direct output to a file. Then write a custom Groovy boolean function that checks the files contents that you can call from your spock test.

Java logging configuration is pretty flexible, so you could probably come up with something that avoided using a temp file if you needed.

Alex Blakemore
  • 11,301
  • 2
  • 26
  • 49
  • 1
    Another way would be to implement a logger implementation of Slf4j that has mocking capabilities, but that's quite a lot of work.. – Wojciech Górski Jul 24 '13 at 16:36