• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2008 The Guava Authors
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package com.google.common.testing;
18 
19 import com.google.common.annotations.GwtCompatible;
20 import java.util.ArrayList;
21 import java.util.Collections;
22 import java.util.List;
23 import java.util.logging.Handler;
24 import java.util.logging.LogRecord;
25 import javax.annotation.CheckForNull;
26 
27 /**
28  * Tests may use this to intercept messages that are logged by the code under test. Example:
29  *
30  * <pre>
31  *   TestLogHandler handler;
32  *
33  *   protected void setUp() throws Exception {
34  *     super.setUp();
35  *     handler = new TestLogHandler();
36  *     SomeClass.logger.addHandler(handler);
37  *     addTearDown(new TearDown() {
38  *       public void tearDown() throws Exception {
39  *         SomeClass.logger.removeHandler(handler);
40  *       }
41  *     });
42  *   }
43  *
44  *   public void test() {
45  *     SomeClass.foo();
46  *     LogRecord firstRecord = handler.getStoredLogRecords().get(0);
47  *     assertEquals("some message", firstRecord.getMessage());
48  *   }
49  * </pre>
50  *
51  * @author Kevin Bourrillion
52  * @since 10.0
53  */
54 @GwtCompatible
55 public class TestLogHandler extends Handler {
56   /** We will keep a private list of all logged records */
57   private final List<LogRecord> list = new ArrayList<>();
58 
59   /** Adds the most recently logged record to our list. */
60   @Override
publish(@heckForNull LogRecord record)61   public synchronized void publish(@CheckForNull LogRecord record) {
62     list.add(record);
63   }
64 
65   @Override
flush()66   public void flush() {}
67 
68   @Override
close()69   public void close() {}
70 
clear()71   public synchronized void clear() {
72     list.clear();
73   }
74 
75   /** Returns a snapshot of the logged records. */
76   /*
77    * TODO(cpovirk): consider higher-level APIs here (say, assertNoRecordsLogged(),
78    * getOnlyRecordLogged(), getAndClearLogRecords()...)
79    *
80    * TODO(cpovirk): consider renaming this method to reflect that it takes a snapshot (and/or return
81    * an ImmutableList)
82    */
getStoredLogRecords()83   public synchronized List<LogRecord> getStoredLogRecords() {
84     List<LogRecord> result = new ArrayList<>(list);
85     return Collections.unmodifiableList(result);
86   }
87 }
88