1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.apache.commons.inject.impl;
18
19 import java.util.ArrayList;
20 import java.util.List;
21
22 import org.apache.commons.inject.api.CommonsInject;
23 import org.apache.commons.inject.api.IInjector;
24 import org.apache.commons.inject.api.ILifecycleController;
25 import org.apache.commons.inject.api.Log4jLoggerModule;
26 import org.apache.commons.inject.api.PostConstructModule;
27 import org.apache.commons.inject.api.bind.IBinder;
28 import org.apache.commons.inject.api.bind.IModule;
29 import org.apache.commons.inject.api.bind.Scopes;
30 import org.apache.log4j.AppenderSkeleton;
31 import org.apache.log4j.BasicConfigurator;
32 import org.apache.log4j.Level;
33 import org.apache.log4j.Logger;
34 import org.apache.log4j.spi.LoggingEvent;
35 import org.junit.Assert;
36 import org.junit.Test;
37
38 public class Log4jLoggerModuleTest {
39 private final List<String> messages = new ArrayList<String>();
40 private void configureLog4j() {
41 BasicConfigurator.configure();
42 final Logger root = Logger.getRootLogger();
43 root.removeAllAppenders();
44 root.addAppender(new AppenderSkeleton(true) {
45
46 @Override
47 public boolean requiresLayout() {
48 return false;
49 }
50
51 @Override
52 public void close() {
53
54 }
55
56 @Override
57 protected void append(LoggingEvent pEvent) {
58 final Level level = pEvent.getLevel();
59 messages.add(level.toString() + "; " + pEvent.getMessage());
60 }
61 });
62 }
63
64 @Test
65 public void testLoggerModule() {
66 configureLog4j();
67 final PostConstructModule module0 = new PostConstructModule();
68 final IModule module1 = new Log4jLoggerModule();
69 final IModule module2 = new IModule(){
70 @Override
71 public void configure(IBinder pBinder) {
72 pBinder.bind(InitializableObject.class).scope(Scopes.PER_CALL);
73 }
74 };
75 final ILifecycleController controller = module0.getLifecycleController();
76 final IInjector injector = CommonsInject.build(module0, module1, module2);
77 final InitializableObject io = injector.getInstance(InitializableObject.class);
78 controller.start();
79 io.run();
80 controller.shutdown();
81 Assert.assertEquals(5, messages.size());
82 Assert.assertEquals("DEBUG; start: ->", messages.get(0));
83 Assert.assertEquals("DEBUG; start: <-", messages.get(1));
84 Assert.assertEquals("DEBUG; run: Running", messages.get(2));
85 Assert.assertEquals("DEBUG; shutdown: ->", messages.get(3));
86 Assert.assertEquals("DEBUG; shutdown: <-", messages.get(4));
87 }
88 }