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