How to set final field in Groovy
Asked Answered
F

1

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?

Falsify answered 24/7, 2013 at 14:21 Comment(2)
What you're doing is an awful hack, so I think all you have as options are awful hacks ;-)Corrosion
True, however the usecase is legitimate - I want to test if a REST controller method logs that it has been called.Outcurve
A
-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.

Adlib answered 24/7, 2013 at 14:50 Comment(1)
Another way would be to implement a logger implementation of Slf4j that has mocking capabilities, but that's quite a lot of work..Outcurve

© 2022 - 2024 — McMap. All rights reserved.