When a Logger (Or any static field) is declared in a class using a static method:
public class Foo {
private static final Logger LOGGER = Logger.getLogger(Foo.getClass);
}
What is the correct way in which I can assert that methods on it are called (for auditing)?
The following will work, but setField appears to be the wrong way to go about it, nullifying the use of the @Tested annotation to allow automatic injection.
@Mocked Logger logger
new Expectations() {
{
setField(unitUnderTest, logger);
}
}
JMockIt seems to provide a solution with @UsingMocksAndStubs(Log4jMocks.class), however this does not allow Expectations on it as it causes calls to getLogger() to return a real, but useless, Logger rather than a mocked instance.
It's simple:
@Test
public void verifyAuditing(@Cascading final Logger logging)
{
// Call code under test which will create auditing records.
new Verifications() {{ logging.info("expected audit info"); }};
}
The use of @Cascading
causes Logger
to be mocked in "cascading" mode, where every method which returns a reference type automatically creates a mocked instance. The initial mocked instance logging
represents all such instances.