1 package org.mod4j.runtime.test;
2
3 import java.util.logging.Handler;
4 import java.util.logging.Level;
5 import java.util.logging.Logger;
6
7 import org.apache.commons.logging.Log;
8 import org.apache.commons.logging.impl.Jdk14Logger;
9 import org.easymock.classextension.EasyMock;
10 import org.junit.After;
11 import org.junit.Before;
12
13 import static org.junit.Assert.assertThat;
14
15 import static org.hamcrest.CoreMatchers.is;
16
17 /**
18 * Base for Tests that need to verify that loglines are properly written.
19 */
20 public abstract class AbstractLoggingTest {
21
22 /**
23 * Can be used to set the {@link Level}. Is set to {@link Level#ALL} in the {@link Before} and the old {@link Level}
24 * will be reset in the {@link After}.
25 */
26 protected Logger logger;
27
28 /** Can be used to 'listen in' on the messages written to the log. Subclass has to do the replay/verify. */
29 protected Handler mockHandler;
30
31 private Level oldLevel;
32
33 /**
34 * Setup environment before tests. If subclasses override this method, don't forget to call super!
35 */
36 @Before
37 public void setUp() {
38 // Get the log for the class under test.
39 final Log log = getLog();
40
41 // If the underlying logging implementation changes, fail.
42 assertThat(log, is(Jdk14Logger.class));
43
44 // Make the logger available to the individual tests.
45 logger = ((Jdk14Logger) log).getLogger();
46
47 // Save oldLevel so we can reset it afterwards.
48 oldLevel = logger.getLevel();
49
50 // Set Level 'all' so we receive all events.
51 logger.setLevel(Level.ALL);
52
53 // Create a MockHandler that can be used to verify log messages.
54 mockHandler = EasyMock.createMock(Handler.class);
55
56 // Add the MockHandler to the logger.
57 logger.addHandler(mockHandler);
58 }
59
60 /**
61 * The {@link Log} we'll work with. Has to be implemented by the subclass.
62 *
63 * @return The {@link Log} we'll work with.
64 */
65 protected abstract Log getLog();
66
67 /**
68 * Cleanup after tests. If subclasses override this method, don't forget to call super!
69 */
70 @After
71 public void tearDown() {
72 // Restore the prior loglevel.
73 logger.setLevel(oldLevel);
74
75 // Remove the mock handler.
76 logger.removeHandler(mockHandler);
77 }
78
79 }