Captured logs
captureLogs records what is logged through SpringLog during each test, so a test can check that code warns or logs an error instead of throwing. In a test class, a @CapturedOutput() field does the same.
Why
Some behaviour is only visible in the log: a warning about a slow payment, an error that is handled and logged instead of thrown. Checking it keeps such code from silently changing.
Example
void main() {
final logs = captureLogs(level: SpringLogLevel.debug); // once, outside the tests
final app = springBootTest(springApplication);
test('warns about slow payments', () {
app.getBean<Checkout>().pay(slowOrder);
expect(logs.messages, contains('slow payment'));
expect(logs.atLevel(SpringLogLevel.warning), hasLength(1));
expect(logs.ofLogger('neon.checkout'), isNotEmpty); // and its child loggers
});
}
@SpringBootTest()
class CheckoutLogTest {
@CapturedOutput()
late CapturedLogs logs; // emptied before every test
@Autowired()
late Checkout checkout;
@Test()
void payingIsLogged() {
checkout.pay(3);
expect(logs.messages, contains('paid 3.0'));
}
}
CapturedLogs
| Member | Gives |
|---|---|
records |
The SpringLogRecords, with level, logger, message, fields and error |
messages |
The messages |
text |
One LEVEL [logger] message line per record |
atLevel(level) |
The records of exactly that level (warnings do not include errors) |
ofLogger(name) |
The records of that logger and the loggers below it |
- Every test starts with an empty capture.
- Records are captured after the loggers' own levels filtered them.
levelsetsSpringLog.levelduring each test and puts the old level back afterwards.- Call
captureLogsonce inmainor agroup, outside the tests.
app.output
app.output is something else: the lines the application printed, such as the failure report of a context that did not start, or the banner when it is on. Each line is also shown when a test fails. The startup information is logged, not printed, so it is in the captured logs, not in output.
In Spring (Java)
Spring Boot's OutputCaptureExtension captures everything the process prints. captureLogs captures SpringLog records only, with their levels and loggers, so assertions do not parse text.