1
2
3
4
5
6
7
8
9
10
11
12
13
14 package ch.qos.logback.classic.pattern;
15
16 import ch.qos.logback.classic.Level;
17 import ch.qos.logback.classic.Logger;
18 import ch.qos.logback.classic.LoggerContext;
19 import ch.qos.logback.classic.spi.ILoggingEvent;
20 import ch.qos.logback.classic.spi.LoggingEvent;
21 import ch.qos.logback.classic.util.LogbackMDCAdapter;
22 import ch.qos.logback.core.testUtil.RandomUtil;
23 import org.junit.jupiter.api.AfterEach;
24 import org.junit.jupiter.api.BeforeEach;
25 import org.junit.jupiter.api.Test;
26 import org.slf4j.MDC;
27
28 import static org.junit.jupiter.api.Assertions.assertEquals;
29 import static org.junit.jupiter.api.Assertions.assertTrue;
30
31 public class MDCConverterTest {
32
33 LoggerContext loggerContext;
34 LogbackMDCAdapter logbackMDCAdapter = new LogbackMDCAdapter();
35 MDCConverter converter;
36 int diff = RandomUtil.getPositiveInt();
37
38 @BeforeEach
39 public void setUp() throws Exception {
40 loggerContext = new LoggerContext();
41 loggerContext.setMDCAdapter(logbackMDCAdapter);
42 converter = new MDCConverter();
43 converter.start();
44 }
45
46 @AfterEach
47 public void tearDown() throws Exception {
48 loggerContext = null;
49 converter.stop();
50 converter = null;
51 }
52
53 @Test
54 public void testConvertWithOneEntry() {
55 String k = "MDCConverterTest_k" + diff;
56 String v = "MDCConverterTest_v" + diff;
57
58 logbackMDCAdapter.put(k, v);
59 ILoggingEvent le = createLoggingEvent();
60 String result = converter.convert(le);
61 assertEquals(k + "=" + v, result);
62 }
63
64 @Test
65 public void testConvertWithMultipleEntries() {
66 logbackMDCAdapter.put("testKey", "testValue");
67 logbackMDCAdapter.put("testKey2", "testValue2");
68 ILoggingEvent le = createLoggingEvent();
69 String result = converter.convert(le);
70 boolean isConform = result.matches("testKey2?=testValue2?, testKey2?=testValue2?");
71 assertTrue( isConform, result + " is not conform");
72 }
73
74 private ILoggingEvent createLoggingEvent() {
75 return new LoggingEvent(this.getClass().getName(), loggerContext.getLogger(Logger.ROOT_LOGGER_NAME), Level.DEBUG,
76 "test message", null, null);
77 }
78 }