Expand my Community achievements bar.

Junit5 Logger

Avatar

Level 3

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.

 

 

 

5 Replies

Avatar

Level 2

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
    @default(values = StringUtils.EMPTY)
    @getter
    private String linkUrl;
 @PostConstruct
    private void init() {
 LOG.info("Inside init method");
}
}

 

Avatar

Community Advisor

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));
}
}

Avatar

Community Advisor

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-annotati...

Avatar

Level 10

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

Avatar

Administrator

@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