Junit5 Logger | Community
Skip to main content
Level 3
June 26, 2024

Junit5 Logger

  • June 26, 2024
  • 5 replies
  • 834 views

Hi Team,

 

How to cover Logger.info(....), Logger.debug() etc using JUNIT5. I tried to search online but could not get a sample example.

 

 

 

and in our Main Class, we have below line for Logger object:

private static final Logger LOGGER= LoggerFactory.getLogger(MyMainClass.class);

 

An example reference will be appreciated.

 

Thank you.

 

 

 

This post is no longer active and is closed to new replies. Need help? Start a new post to ask your question.

5 replies

Level 2
June 26, 2024

Below is the example snippet how to use logger with info similarly u can use for other levels too debug/error.

import org.slf4j.Logger; import org.slf4j.LoggerFactory; @Model(adaptables = SlingHttpServletRequest.class) public class GetUrl { private static final Logger LOG = LoggerFactory.getLogger(GetUrl.class); @RequestAttribute @1497330(values = StringUtils.EMPTY) @14766979 private String linkUrl; @PostConstruct private void init() { LOG.info("Inside init method"); } }

 

MukeshYadav_
Community Advisor
Community Advisor
June 26, 2024

Hi @arvindpandey , 

You may try /get help from default sample code provided by Adobe.

 

private TestLogger logger = TestLoggerFactory.getTestLogger(fixture.getClass());

 


@ExtendWith(AemContextExtension.class)
class SimpleScheduledTaskTest {

private SimpleScheduledTask fixture = new SimpleScheduledTask();

private TestLogger logger = TestLoggerFactory.getTestLogger(fixture.getClass());

@BeforeEach
void setup() {
TestLoggerFactory.clear();
}

@Test
void run() {
SimpleScheduledTask.Config config = mock(SimpleScheduledTask.Config.class);
when(config.myParameter()).thenReturn("parameter value");

fixture.activate(config);
fixture.run();

List<LoggingEvent> events = logger.getLoggingEvents();
assertEquals(1, events.size());
LoggingEvent event = events.get(0);
assertEquals(Level.DEBUG, event.getLevel());
assertEquals(1, event.getArguments().size());
assertEquals("parameter value", event.getArguments().get(0));
}
}
MukeshYadav_
Community Advisor
Community Advisor
June 26, 2024

Hi,

You may try static mocking as well but for this need to enable mock-maker-inline

 

Logger mockedLogger = Mockito.mock(Logger.class);

Ref- https://stackoverflow.com/questions/66816515/how-to-mock-logger-when-created-with-the-slf4j-annotation

Level 9
June 30, 2024

Were you able to resolve it ? I managed to create a test logger and it just resolved it 

kautuk_sahni
Community Manager
Community Manager
July 16, 2024

@arvindpandey Did you find the suggestion helpful? Please let us know if you require more information. Otherwise, please mark the answer as correct for posterity. If you've discovered a solution yourself, we would appreciate it if you could share it with the community. Thank you!

Kautuk Sahni