1   package ch.qos.logback.classic;
2   
3   import java.io.ByteArrayInputStream;
4   import java.io.ByteArrayOutputStream;
5   import java.io.IOException;
6   import java.io.ObjectInputStream;
7   import java.io.ObjectOutputStream;
8   
9   import org.junit.After;
10  import org.junit.Before;
11  import org.junit.Test;
12  
13  public class LoggerSerializationTest {
14  
15    LoggerContext lc;
16    Logger logger;
17  
18    ByteArrayOutputStream bos;
19    ObjectOutputStream oos;
20    ObjectInputStream inputStream;
21  
22    @Before
23    public void setUp() throws Exception {
24      lc = new LoggerContext();
25      lc.setName("testContext");
26      logger = lc.getLogger(LoggerSerializationTest.class);
27      // create the byte output stream
28      bos = new ByteArrayOutputStream();
29      oos = new ObjectOutputStream(bos);
30    }
31  
32    @After
33    public void tearDown() throws Exception {
34      lc = null;
35      logger = null;
36      oos.close();
37    }
38    
39    @Test
40    public void serialization() throws IOException, ClassNotFoundException {
41      Foo foo = new Foo(logger);
42      foo.doFoo();
43      Foo fooBack = writeAndRead(foo);
44      fooBack.doFoo();
45    }
46  
47    private Foo writeAndRead(Foo foo) throws IOException,
48        ClassNotFoundException {
49      oos.writeObject(foo);
50      ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
51      inputStream = new ObjectInputStream(bis);
52  
53      return (Foo) inputStream.readObject();
54    }
55  }