I have the following code:
@Component
@Slf4j
public class MyClass {
private OtherClass otherClass;
@Autowired
public MyClass(OtherClass otherClass) {
this.otherClass = otherClass;
}
public void start() {
try {
otherClass.execute();
} catch (FeatureException exception) {
log.warn(exception.getMessage());
}
}
I want do test to verify the log message. I dont know how.
Thanks
Use Log Annotations. Lombok provides several log annotations to work with different logging libraries.
ALL: in unit tests you can change the log level of the logger, to verify that when a certain log level is set, certain messages will no longer be logged. For example, if the log level were to be set to WARN, then the FruitLogger should no longer log the message body.
Annotation Type Slf4jCauses lombok to generate a logger field. Complete documentation is found at the project lombok features page for lombok log annotations.
LogCaptor is a library which will enable you to easily capture logging entries for unit testing purposes.
The SLF4J project recommends using the library SLF4J Test for this use case.
In your case (using Hamcrest and Mockito as well):
public class MyClassTest {
TestLogger logger = TestLoggerFactory.getTestLogger(MyClass.class);
@Test
public void testStart_loggingFailureMessage() {
OtherClass otherClass = mock(OtherClass.class);
MyClass myClass = new MyClass(otherClass);
when(otherClass.execute()).thenThrow(new FeatureException("Some text"));
myClass.start();
assertThat(logger.getLoggingEvents(), is(asList(LoggingEvent.warn("Some text"))));
}
@After
public void clearLoggers() {
TestLoggerFactory.clear();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With