|
| 1 | +package com.baeldung.logback; |
| 2 | + |
| 3 | +import ch.qos.logback.classic.Level; |
| 4 | +import ch.qos.logback.classic.LoggerContext; |
| 5 | +import ch.qos.logback.classic.spi.LoggingEvent; |
| 6 | +import ch.qos.logback.core.BasicStatusManager; |
| 7 | +import org.junit.After; |
| 8 | +import org.junit.Before; |
| 9 | +import org.junit.Test; |
| 10 | + |
| 11 | +import static org.junit.Assert.assertEquals; |
| 12 | +import static org.junit.Assert.assertTrue; |
| 13 | + |
| 14 | +public class MapAppenderTest { |
| 15 | + |
| 16 | + private LoggerContext ctx; |
| 17 | + |
| 18 | + private MapAppender mapAppender = new MapAppender(); |
| 19 | + |
| 20 | + private LoggingEvent event; |
| 21 | + |
| 22 | + @Before |
| 23 | + public void setUp() throws Exception { |
| 24 | + ctx = new LoggerContext(); |
| 25 | + ctx.setName("test context"); |
| 26 | + ctx.setStatusManager(new BasicStatusManager()); |
| 27 | + mapAppender.setContext(ctx); |
| 28 | + mapAppender.setPrefix("prefix"); |
| 29 | + event = new LoggingEvent("fqcn", ctx.getLogger("logger"), Level.INFO, "Test message for logback appender", null, new Object[0]); |
| 30 | + ctx.start(); |
| 31 | + } |
| 32 | + |
| 33 | + @After |
| 34 | + public void tearDown() throws Exception { |
| 35 | + ctx.stop(); |
| 36 | + mapAppender.stop(); |
| 37 | + } |
| 38 | + |
| 39 | + @Test |
| 40 | + public void whenPrefixIsNull_thenMapAppenderDoesNotLog() throws Exception { |
| 41 | + mapAppender.setPrefix(null); |
| 42 | + mapAppender.append(event); |
| 43 | + assertTrue(mapAppender.getEventMap().isEmpty()); |
| 44 | + } |
| 45 | + |
| 46 | + @Test |
| 47 | + public void whenPrefixIsEmpty_thenMapAppenderDoesNotLog() throws Exception { |
| 48 | + mapAppender.setPrefix(""); |
| 49 | + mapAppender.append(event); |
| 50 | + assertTrue(mapAppender.getEventMap().isEmpty()); |
| 51 | + } |
| 52 | + |
| 53 | + @Test |
| 54 | + public void whenLogMessageIsEmitted_thenMapAppenderReceivesMessage() throws Exception { |
| 55 | + mapAppender.append(event); |
| 56 | + assertEquals(mapAppender.getEventMap().size(), 1); |
| 57 | + mapAppender.getEventMap().forEach((k, v) -> assertTrue(k.startsWith("prefix"))); |
| 58 | + } |
| 59 | + |
| 60 | +} |
0 commit comments