问题
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?
回答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.
来源:https://stackoverflow.com/questions/17836764/how-to-set-final-field-in-groovy