我有一些测试中的代码,它调用Java记录器来报告其状态。 在JUnit测试代码中,我想验证在此记录器中是否输入了正确的日志。以下内容:
methodUnderTest(bool x){
if(x)
logger.info("x happened")
}
@Test tester(){
// perhaps setup a logger first.
methodUnderTest(true);
assertXXXXXX(loggedLevel(),Level.INFO);
}
我认为这可以通过特殊改编的记录器(或处理程序或格式化程序)来完成,但我更愿意重用已经存在的解决方案。 (而且,说实话,我不清楚如何从记录器获取logRecord,但假设这是可能的。)
答案 0 :(得分:128)
我也需要这几次。我在下面放了一个小样本,您需要根据自己的需要进行调整。基本上,您可以创建自己的Appender
并将其添加到所需的记录器中。如果您想要收集所有内容,则根记录器是一个很好的起点,但如果您愿意,可以使用更具体的记录器。完成后不要忘记删除Appender,否则可能会造成内存泄漏。以下我在测试中完成了这项工作,但setUp
或@Before
以及tearDown
或@After
可能是更好的地方,具体取决于您的需求。
此外,下面的实现收集内存中List
的所有内容。如果你正在记录很多,你可以考虑添加一个过滤器来删除无聊的条目,或者将日志写入磁盘上的临时文件(提示:LoggingEvent
是Serializable
,所以你应该能够如果您的日志消息是,则只序列化事件对象。)
import org.apache.log4j.AppenderSkeleton;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.log4j.spi.LoggingEvent;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
public class MyTest {
@Test
public void test() {
final TestAppender appender = new TestAppender();
final Logger logger = Logger.getRootLogger();
logger.addAppender(appender);
try {
Logger.getLogger(MyTest.class).info("Test");
}
finally {
logger.removeAppender(appender);
}
final List<LoggingEvent> log = appender.getLog();
final LoggingEvent firstLogEntry = log.get(0);
assertThat(firstLogEntry.getLevel(), is(Level.INFO));
assertThat((String) firstLogEntry.getMessage(), is("Test"));
assertThat(firstLogEntry.getLoggerName(), is("MyTest"));
}
}
class TestAppender extends AppenderSkeleton {
private final List<LoggingEvent> log = new ArrayList<LoggingEvent>();
@Override
public boolean requiresLayout() {
return false;
}
@Override
protected void append(final LoggingEvent loggingEvent) {
log.add(loggingEvent);
}
@Override
public void close() {
}
public List<LoggingEvent> getLog() {
return new ArrayList<LoggingEvent>(log);
}
}
答案 1 :(得分:32)
非常感谢这些(令人惊讶的)快速而有用的答案;他们让我以正确的方式解决问题。
代码库是我想要使用它,使用java.util.logging作为其记录器机制,我觉得在这些代码中没有足够的东西将它完全改为log4j或logger接口/外观。但基于这些建议,我'hack-up'一个j.u.l.handler扩展,这可以作为一种享受。
简短摘要如下。扩展java.util.logging.Handler
:
class LogHandler extends Handler
{
Level lastLevel = Level.FINEST;
public Level checkLevel() {
return lastLevel;
}
public void publish(LogRecord record) {
lastLevel = record.getLevel();
}
public void close(){}
public void flush(){}
}
显然,您可以从LogRecord
存储您想要/想要/需要的内容,或者将它们全部压缩到堆栈中,直到出现溢出。
在准备junit-test时,您需要创建一个java.util.logging.Logger
并为其添加一个新的LogHandler
:
@Test tester() {
Logger logger = Logger.getLogger("my junit-test logger");
LogHandler handler = new LogHandler();
handler.setLevel(Level.ALL);
logger.setUseParentHandlers(false);
logger.addHandler(handler);
logger.setLevel(Level.ALL);
对setUseParentHandlers()
的调用是使正常处理程序静音,以便(对于此junit-test运行)不会发生不必要的日志记录。做你的测试代码需要使用这个记录器,运行测试和assertEquality:
libraryUnderTest.setLogger(logger);
methodUnderTest(true); // see original question.
assertEquals("Log level as expected?", Level.INFO, handler.checkLevel() );
}
(当然,你会将这项工作的大部分内容转移到@Before
方法并进行各种其他改进,但这样会使这个演示文稿变得混乱。)
答案 2 :(得分:22)
这是一个简单高效的Logback解决方案。
不需要添加/创建任何新类。
它依赖于ListAppender
:一个白盒回溯追加器,其中,在public List
字段中添加了日志条目,我们可以使用该条目进行断言。
这是一个简单的例子。
Foo类:
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Foo {
static final Logger LOGGER = LoggerFactory.getLogger(Foo .class);
public void doThat() {
logger.info("start");
//...
logger.info("finish");
}
}
FooTest类:
import org.slf4j.LoggerFactory;
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.read.ListAppender;
public class FooTest {
@Test
void doThat() throws Exception {
// get Logback Logger
Logger fooLogger = (Logger) LoggerFactory.getLogger(Foo.class);
// create and start a ListAppender
ListAppender<ILoggingEvent> listAppender = new ListAppender<>();
listAppender.start();
// add the appender to the logger
fooLogger.addAppender(listAppender);
// call method under test
Foo foo = new Foo();
foo.doThat();
// JUnit assertions
List<ILoggingEvent> logsList = listAppender.list;
assertEquals("start", logsList.get(0)
.getMessage());
assertEquals(Level.INFO, logsList.get(0)
.getLevel());
assertEquals("finish", logsList.get(1)
.getMessage());
assertEquals(Level.INFO, logsList.get(1)
.getLevel());
}
}
JUnit断言听起来不太适合断言列表元素的某些特定属性。
匹配器/断言库,例如AssertJ或Hamcrest似乎更好:
使用AssertJ,它将是:
import org.assertj.core.api.Assertions;
Assertions.assertThat(listAppender.list)
.extracting(ILoggingEvent::getMessage, ILoggingEvent::getLevel)
.containsExactly(Tuple.tuple("start", Level.INFO), Tuple.tuple("finish", Level.INFO));
答案 3 :(得分:16)
有效地,您正在测试依赖类的副作用。对于单元测试,您只需要验证
使用正确的参数调用
logger.info()
。因此,使用模拟框架来模拟记录器,这将允许您测试自己的类的行为。
答案 4 :(得分:13)
另一种选择是模拟Appender并验证是否已将消息记录到此appender。 Log4j 1.2.x和mockito的示例:
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import org.apache.log4j.Appender;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.log4j.spi.LoggingEvent;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
public class MyTest {
private final Appender appender = mock(Appender.class);
private final Logger logger = Logger.getRootLogger();
@Before
public void setup() {
logger.addAppender(appender);
}
@Test
public void test() {
// when
Logger.getLogger(MyTest.class).info("Test");
// then
ArgumentCaptor<LoggingEvent> argument = ArgumentCaptor.forClass(LoggingEvent.class);
verify(appender).doAppend(argument.capture());
assertEquals(Level.INFO, argument.getValue().getLevel());
assertEquals("Test", argument.getValue().getMessage());
assertEquals("MyTest", argument.getValue().getLoggerName());
}
@After
public void cleanup() {
logger.removeAppender(appender);
}
}
答案 5 :(得分:10)
模拟是一个选项,虽然它很难,因为记录器通常是私有静态最终 - 所以设置模拟记录器不会是小菜一碟,或者需要修改被测试的类。
您可以创建自定义Appender(或其任何名称)并注册它 - 通过仅测试配置文件或运行时(在某种程度上,取决于日志记录框架)。 然后你可以得到那个appender(静态地,如果在配置文件中声明,或者通过它的当前引用,如果你正在插入运行时),并验证它的内容。
答案 6 :(得分:8)
对于Junit 5(Jupiter),Spring的OutputCaptureExtension非常有用。从Spring Boot 2.2开始可用,并且在spring-boot-test工件中可用。
示例(取自javadoc):
is_front_page()
答案 7 :(得分:5)
受@ RonaldBlaschke解决方案的启发,我想出了这个:
public class Log4JTester extends ExternalResource {
TestAppender appender;
@Override
protected void before() {
appender = new TestAppender();
final Logger rootLogger = Logger.getRootLogger();
rootLogger.addAppender(appender);
}
@Override
protected void after() {
final Logger rootLogger = Logger.getRootLogger();
rootLogger.removeAppender(appender);
}
public void assertLogged(Matcher<String> matcher) {
for(LoggingEvent event : appender.events) {
if(matcher.matches(event.getMessage())) {
return;
}
}
fail("No event matches " + matcher);
}
private static class TestAppender extends AppenderSkeleton {
List<LoggingEvent> events = new ArrayList<LoggingEvent>();
@Override
protected void append(LoggingEvent event) {
events.add(event);
}
@Override
public void close() {
}
@Override
public boolean requiresLayout() {
return false;
}
}
}
...允许你这样做:
@Rule public Log4JTester logTest = new Log4JTester();
@Test
public void testFoo() {
user.setStatus(Status.PREMIUM);
logTest.assertLogged(
stringContains("Note added to account: premium customer"));
}
你可能会以更聪明的方式使用hamcrest,但我已经把它留在了这里。
答案 8 :(得分:4)
正如其他人所提到的,你可以使用一个模拟框架。为了完成这项工作,你必须在课堂上公开记录器(尽管我更倾向于将其打包为私有而不是创建公共设置器)。
另一种解决方案是手动创建假记录器。你必须编写假记录器(更多夹具代码),但在这种情况下,我更喜欢测试的增强可读性与模拟框架中保存的代码。
我会做这样的事情:
class FakeLogger implements ILogger {
public List<String> infos = new ArrayList<String>();
public List<String> errors = new ArrayList<String>();
public void info(String message) {
infos.add(message);
}
public void error(String message) {
errors.add(message);
}
}
class TestMyClass {
private MyClass myClass;
private FakeLogger logger;
@Before
public void setUp() throws Exception {
myClass = new MyClass();
logger = new FakeLogger();
myClass.logger = logger;
}
@Test
public void testMyMethod() {
myClass.myMethod(true);
assertEquals(1, logger.infos.size());
}
}
答案 9 :(得分:4)
这是我为回归所做的。
我创建了一个TestAppender类:
public class TestAppender extends AppenderBase<ILoggingEvent> {
private Stack<ILoggingEvent> events = new Stack<ILoggingEvent>();
@Override
protected void append(ILoggingEvent event) {
events.add(event);
}
public void clear() {
events.clear();
}
public ILoggingEvent getLastEvent() {
return events.pop();
}
}
然后在我的testng单元测试类的父级中创建了一个方法:
protected TestAppender testAppender;
@BeforeClass
public void setupLogsForTesting() {
Logger root = (Logger)LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
testAppender = (TestAppender)root.getAppender("TEST");
if (testAppender != null) {
testAppender.clear();
}
}
我在src / test / resources中定义了一个logback-test.xml文件,并添加了一个测试appender:
<appender name="TEST" class="com.intuit.icn.TestAppender">
<encoder>
<pattern>%m%n</pattern>
</encoder>
</appender>
并将此appender添加到root appender:
<root>
<level value="error" />
<appender-ref ref="STDOUT" />
<appender-ref ref="TEST" />
</root>
现在,在我从父测试类扩展的测试类中,我可以获取appender并记录最后一条消息并验证消息,级别,throwable。
ILoggingEvent lastEvent = testAppender.getLastEvent();
assertEquals(lastEvent.getMessage(), "...");
assertEquals(lastEvent.getLevel(), Level.WARN);
assertEquals(lastEvent.getThrowableProxy().getMessage(), "...");
答案 10 :(得分:3)
检查这个库https://github.com/Hakky54/log-captor
在您的 Maven 文件中包含库的参考:
<dependency>
<groupId>io.github.hakky54</groupId>
<artifactId>logcaptor</artifactId>
<version>2.5.0</version>
<scope>test</scope>
</dependency>
在java代码测试方法中你应该包括这个:
LogCaptor logCaptor = LogCaptor.forClass(MyClass.class);
// do the test logic....
assertThat(logCaptor.getLogs()).contains("Some log to assert");
答案 11 :(得分:3)
哇。我不确定为什么这么难。我发现我无法使用上面的任何代码示例,因为我在slf4j上使用log4j2。这是我的解决方案:
public class SpecialLogServiceTest {
@Mock
private Appender appender;
@Captor
private ArgumentCaptor<LogEvent> captor;
@InjectMocks
private SpecialLogService specialLogService;
private LoggerConfig loggerConfig;
@Before
public void setUp() {
// prepare the appender so Log4j likes it
when(appender.getName()).thenReturn("MockAppender");
when(appender.isStarted()).thenReturn(true);
when(appender.isStopped()).thenReturn(false);
final LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
final Configuration config = ctx.getConfiguration();
loggerConfig = config.getLoggerConfig("org.example.SpecialLogService");
loggerConfig.addAppender(appender, AuditLogCRUDService.LEVEL_AUDIT, null);
}
@After
public void tearDown() {
loggerConfig.removeAppender("MockAppender");
}
@Test
public void writeLog_shouldCreateCorrectLogMessage() throws Exception {
SpecialLog specialLog = new SpecialLogBuilder().build();
String expectedLog = "this is my log message";
specialLogService.writeLog(specialLog);
verify(appender).append(captor.capture());
assertThat(captor.getAllValues().size(), is(1));
assertThat(captor.getAllValues().get(0).getMessage().toString(), is(expectedLog));
}
}
答案 12 :(得分:3)
对于log4j2,解决方案略有不同,因为AppenderSkeleton不再可用。此外,如果您期望多条日志消息,则使用Mockito或类似的库来创建带有ArgumentCaptor的Appender将无法工作,因为MutableLogEvent会在多条日志消息上重用。我发现log4j2的最佳解决方案是:
private static MockedAppender mockedAppender;
private static Logger logger;
@Before
public void setup() {
mockedAppender.message.clear();
}
/**
* For some reason mvn test will not work if this is @Before, but in eclipse it works! As a
* result, we use @BeforeClass.
*/
@BeforeClass
public static void setupClass() {
mockedAppender = new MockedAppender();
logger = (Logger)LogManager.getLogger(MatchingMetricsLogger.class);
logger.addAppender(mockedAppender);
logger.setLevel(Level.INFO);
}
@AfterClass
public static void teardown() {
logger.removeAppender(mockedAppender);
}
@Test
public void test() {
// do something that causes logs
for (String e : mockedAppender.message) {
// add asserts for the log messages
}
}
private static class MockedAppender extends AbstractAppender {
List<String> message = new ArrayList<>();
protected MockedAppender() {
super("MockedAppender", null, null);
}
@Override
public void append(LogEvent event) {
message.add(event.getMessage().getFormattedMessage());
}
}
答案 13 :(得分:3)
对于我,您可以使用JUnit
Mockito
来简化测试。
我建议以下解决方案:
import org.apache.log4j.Appender;
import org.apache.log4j.Level;
import org.apache.log4j.LogManager;
import org.apache.log4j.spi.LoggingEvent;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.tuple;
import static org.mockito.Mockito.times;
@RunWith(MockitoJUnitRunner.class)
public class MyLogTest {
private static final String FIRST_MESSAGE = "First message";
private static final String SECOND_MESSAGE = "Second message";
@Mock private Appender appender;
@Captor private ArgumentCaptor<LoggingEvent> captor;
@InjectMocks private MyLog;
@Before
public void setUp() {
LogManager.getRootLogger().addAppender(appender);
}
@After
public void tearDown() {
LogManager.getRootLogger().removeAppender(appender);
}
@Test
public void shouldLogExactlyTwoMessages() {
testedClass.foo();
then(appender).should(times(2)).doAppend(captor.capture());
List<LoggingEvent> loggingEvents = captor.getAllValues();
assertThat(loggingEvents).extracting("level", "renderedMessage").containsExactly(
tuple(Level.INFO, FIRST_MESSAGE)
tuple(Level.INFO, SECOND_MESSAGE)
);
}
}
这就是为什么我们对不同邮件数量
的测试具有良好的灵活性的原因答案 14 :(得分:2)
Here is the sample code to mock log, irrespective of the version used for junit or sping, springboot.
import ch.qos.logback.classic.spi.LoggingEvent;
import ch.qos.logback.core.Appender;
import org.mockito.ArgumentMatcher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.junit.Test;
import static org.mockito.Matchers.argThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
public class MyTest {
private static Logger logger = LoggerFactory.getLogger(MyTest.class);
@Test
public void testSomething() {
ch.qos.logback.classic.Logger root = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger(ch.qos.logback.classic.Logger.ROOT_LOGGER_NAME);
final Appender mockAppender = mock(Appender.class);
when(mockAppender.getName()).thenReturn("MOCK");
root.addAppender(mockAppender);
//... do whatever you need to trigger the log
verify(mockAppender).doAppend(argThat(new ArgumentMatcher() {
@Override
public boolean matches(final Object argument) {
return ((LoggingEvent)argument).getFormattedMessage().contains("Hey this is the message I want to see");
}
}));
}
}
答案 15 :(得分:1)
我也遇到了同样的挑战,并最终出现在此页面上。尽管我回答问题已有11年,但我认为也许对其他人仍然有用。我发现Logback和ListAppander的davidxxx
的答案非常有用。我对多个项目使用了相同的配置,但是当我需要更改某些内容时,复制/粘贴并维护所有版本并不是很有趣。我认为最好建立一个图书馆并回馈社区。它与SLFJ4,Log4j,Log4j2,Java Util日志记录以及Lombok注释一起使用。请在这里看看:LogCaptor
示例情况:
public class FooService {
private static final Logger LOGGER = LoggerFactory.getLogger(FooService.class);
public void sayHello() {
LOGGER.info("Keyboard not responding. Press any key to continue...");
LOGGER.warn("Congratulations, you are pregnant!");
}
}
使用LogCaptor的示例单元测试:
public class FooServiceTest {
private LogCaptor logCaptor = LogCaptor.forClass(FooService.class);
@Test
public void logInfoAndWarnMessages() {
String expectedInfoMessage = "Keyboard not responding. Press any key to continue...";
String expectedWarnMessage = "Congratulations, you are pregnant!";
FooService fooService = new FooService();
fooService.sayHello();
List<String> infoLogMessages = logCaptor.getInfoLogs();
List<String> warnLogMessages = logCaptor.getWarnLogs();
List<String> allLogMessages = logCaptor.getLogs();
assertThat(infoLogMessages).containsExactly(expectedInfoMessage);
assertThat(warnLogMessages).containsExactly(expectedWarnMessage);
assertThat(allLogMessages).containsExactly(expectedWarnMessage, expectedInfoMessage);
}
}
我不确定是否应该在此处发布此内容,因为它也可以被视为推广“我的库”的一种方法,但我认为这对面临相同挑战的开发人员可能会有所帮助。
答案 16 :(得分:0)
如果您使用java.util.logging.Logger
这篇文章可能会非常有用,它会创建一个新的处理程序并在日志输出上进行断言:
http://octodecillion.com/blog/jmockit-test-logging/
答案 17 :(得分:0)
您可能尝试测试两件事。
这两件事实际上是不同的事情,因此可以单独测试。但是,测试第二个(消息文本)是如此有问题,我建议不要这样做。对消息文本的测试最终将包括检查一个文本字符串(预期的消息文本)是否与日志代码中使用的文本字符串相同,或者可以从中简单地派生出来。
请注意,让您的程序代码(可能实现一些业务逻辑)直接调用文本日志记录界面是很糟糕的设计(但不幸的是非常普遍)。负责业务逻辑的代码还决定一些日志记录策略和日志消息的文本。它将业务逻辑与用户界面代码混合在一起(是的,日志消息是程序用户界面的一部分)。这些事情应该是分开的。
因此,我建议业务逻辑不直接生成日志消息的文本。而是将其委托给日志记录对象。
implements
和interface
,它描述了您的业务逻辑可能使用的内部API。interface
。然后,您可以通过创建模拟记录器来测试您的业务逻辑类是否正确地告诉日志记录接口,该模拟记录器实现了内部日志记录API,并在测试的设置阶段使用依赖注入。
像这样:
public class MyService {// The class we want to test
private final MyLogger logger;
public MyService(MyLogger logger) {
this.logger = Objects.requireNonNull(logger);
}
public void performTwiddleOperation(Foo foo) {// The method we want to test
...// The business logic
logger.performedTwiddleOperation(foo);
}
};
public interface MyLogger {
public void performedTwiddleOperation(Foo foo);
...
};
public final class MySl4jLogger: implements MyLogger {
...
@Override
public void performedTwiddleOperation(Foo foo) {
logger.info("twiddled foo " + foo.getId());
}
}
public final void MyProgram {
public static void main(String[] argv) {
...
MyLogger logger = new MySl4jLogger(...);
MyService service = new MyService(logger);
startService(service);// or whatever you must do
...
}
}
public class MyServiceTest {
...
static final class MyMockLogger: implements MyLogger {
private Food.id id;
private int nCallsPerformedTwiddleOperation;
...
@Override
public void performedTwiddleOperation(Foo foo) {
id = foo.id;
++nCallsPerformedTwiddleOperation;
}
void assertCalledPerformedTwiddleOperation(Foo.id id) {
assertEquals("Called performedTwiddleOperation", 1, nCallsPerformedTwiddleOperation);
assertEquals("Called performedTwiddleOperation with correct ID", id, this.id);
}
};
@Test
public void testPerformTwiddleOperation_1() {
// Setup
MyMockLogger logger = new MyMockLogger();
MyService service = new MyService(logger);
Foo.Id id = new Foo.Id(...);
Foo foo = new Foo(id, 1);
// Execute
service.performedTwiddleOperation(foo);
// Verify
...
logger.assertCalledPerformedTwiddleOperation(id);
}
}
答案 18 :(得分:0)
如果我想要做的就是看到记录了一些字符串(而不是验证确切的日志语句,这太脆弱了),我做了什么是将StdOut重定向到缓冲区,执行包含,然后重置StdOut:
PrintStream original = System.out;
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
System.setOut(new PrintStream(buffer));
// Do something that logs
assertTrue(buffer.toString().contains(myMessage));
System.setOut(original);
答案 19 :(得分:0)
Log4J2的API略有不同。另外,您可能正在使用其异步附加程序。我为此创建了一个锁存的附加器:
public static class LatchedAppender extends AbstractAppender implements AutoCloseable {
private final List<LogEvent> messages = new ArrayList<>();
private final CountDownLatch latch;
private final LoggerConfig loggerConfig;
public LatchedAppender(Class<?> classThatLogs, int expectedMessages) {
this(classThatLogs, null, null, expectedMessages);
}
public LatchedAppender(Class<?> classThatLogs, Filter filter, Layout<? extends Serializable> layout, int expectedMessages) {
super(classThatLogs.getName()+"."+"LatchedAppender", filter, layout);
latch = new CountDownLatch(expectedMessages);
final LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
final Configuration config = ctx.getConfiguration();
loggerConfig = config.getLoggerConfig(LogManager.getLogger(classThatLogs).getName());
loggerConfig.addAppender(this, Level.ALL, ThresholdFilter.createFilter(Level.ALL, null, null));
start();
}
@Override
public void append(LogEvent event) {
messages.add(event);
latch.countDown();
}
public List<LogEvent> awaitMessages() throws InterruptedException {
assertTrue(latch.await(10, TimeUnit.SECONDS));
return messages;
}
@Override
public void close() {
stop();
loggerConfig.removeAppender(this.getName());
}
}
像这样使用它:
try (LatchedAppender appender = new LatchedAppender(ClassUnderTest.class, 1)) {
ClassUnderTest.methodThatLogs();
List<LogEvent> events = appender.awaitMessages();
assertEquals(1, events.size());
//more assertions here
}//appender removed
答案 20 :(得分:0)
模拟Appender可以帮助捕获日志行。 在http://clearqa.blogspot.co.uk/2016/12/test-log-lines.html
上查找示例// Fully working test at: https://github.com/njaiswal/logLineTester/blob/master/src/test/java/com/nj/Utils/UtilsTest.java
@Test
public void testUtilsLog() throws InterruptedException {
Logger utilsLogger = (Logger) LoggerFactory.getLogger("com.nj.utils");
final Appender mockAppender = mock(Appender.class);
when(mockAppender.getName()).thenReturn("MOCK");
utilsLogger.addAppender(mockAppender);
final List<String> capturedLogs = Collections.synchronizedList(new ArrayList<>());
final CountDownLatch latch = new CountDownLatch(3);
//Capture logs
doAnswer((invocation) -> {
LoggingEvent loggingEvent = invocation.getArgumentAt(0, LoggingEvent.class);
capturedLogs.add(loggingEvent.getFormattedMessage());
latch.countDown();
return null;
}).when(mockAppender).doAppend(any());
//Call method which will do logging to be tested
Application.main(null);
//Wait 5 seconds for latch to be true. That means 3 log lines were logged
assertThat(latch.await(5L, TimeUnit.SECONDS), is(true));
//Now assert the captured logs
assertThat(capturedLogs, hasItem(containsString("One")));
assertThat(capturedLogs, hasItem(containsString("Two")));
assertThat(capturedLogs, hasItem(containsString("Three")));
}
答案 21 :(得分:0)
我为log4j回答了类似的问题,请参见how-can-i-test-with-junit-that-a-warning-was-logged-with-log4
这是较新的示例,它使用Log4j2(已通过2.11.2测试)和junit 5;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.core.Logger;
import org.apache.logging.log4j.core.*;
import org.apache.logging.log4j.core.appender.AbstractAppender;
import org.apache.logging.log4j.core.config.Configuration;
import org.apache.logging.log4j.core.config.LoggerConfig;
import org.apache.logging.log4j.core.config.plugins.Plugin;
import org.apache.logging.log4j.core.config.plugins.PluginAttribute;
import org.apache.logging.log4j.core.config.plugins.PluginElement;
import org.apache.logging.log4j.core.config.plugins.PluginFactory;
import org.hamcrest.core.Is;
import org.junit.Assert;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.List;
import static org.junit.Assert.*;
class TestLogger {
private TestAppender testAppender;
private LoggerConfig loggerConfig;
private final Logger logger = (Logger)
LogManager.getLogger(ClassUnderTest.class);
@Test
@DisplayName("Test Log Junit5 and log4j2")
void test() {
ClassUnderTest.logMessage();
final LogEvent loggingEvent = testAppender.events.get(0);
//asset equals 1 because log level is info, change it to debug and
//the test will fail
assertTrue("Unexpected empty log",testAppender.events.size()==1);
assertEquals("Unexpected log level",Level.INFO,loggingEvent.getLevel());
assertEquals("Unexpected log message"
,loggingEvent.getMessage().toString()
,"Hello Test");
}
@BeforeEach
private void setup() {
testAppender = new TestAppender("test", null);
final LoggerContext context = logger.getContext();
final Configuration configuration = context.getConfiguration();
loggerConfig = configuration.getLoggerConfig(logger.getName());
loggerConfig.setLevel(Level.INFO);
loggerConfig.addAppender(testAppender,Level.INFO,null);
testAppender.start();
context.updateLoggers();
}
@AfterEach
void after(){
logAppender.stop();
loggerConfig.removeAppender("TestAppender");
final LoggerContext context = logger.getContext();
context.updateLoggers();
}
@Plugin( name = "TestAppender", category = Core.CATEGORY_NAME, elementType = Appender.ELEMENT_TYPE)
static class TestAppender extends AbstractAppender {
List<LogEvent> events = new ArrayList();
protected TestAppender(String name, Filter filter) {
super(name, filter, null);
}
@PluginFactory
public static TestAppender createAppender(
@PluginAttribute("name") String name,
@PluginElement("Filter") Filter filter) {
return new TestAppender(name, filter);
}
@Override
public void append(LogEvent event) {
events.add(event);
}
}
static class ClassUnderTest {
private static final Logger LOGGER = (Logger) LogManager.getLogger(ClassUnderTest.class);
public static void logMessage(){
LOGGER.info("Hello Test");
LOGGER.debug("Hello Test");
}
}
}
答案 22 :(得分:0)
请注意,在Log4J 2.x中,公共接口org.apache.logging.log4j.Logger
不包括setAppender()
和removeAppender()
方法。
但是,如果您没有做任何花哨的事情,您应该可以将其强制转换为实现类org.apache.logging.log4j.core.Logger
,该类确实公开了这些方法。
// Import the implementation class rather than the API interface
import org.apache.logging.log4j.core.Logger;
// Cast logger to implementation class to get access to setAppender/removeAppender
Logger log = (Logger) LogManager.getLogger(MyClassUnderTest.class);
// Set up the mock appender, stubbing some methods Log4J needs internally
Appender appender = mock(Appender.class);
when(appender.getName()).thenReturn("Mock Appender");
when(appender.isStarted()).thenReturn(true);
log.addAppender(appender);
try {
new MyClassUnderTest().doSomethingThatShouldLogAnError();
} finally {
log.removeAppender(appender);
}
// Verify that we got an error with the expected message
ArgumentCaptor<LogEvent> logEventCaptor = ArgumentCaptor.forClass(LogEvent.class);
verify(appender).append(logEventCaptor.capture());
LogEvent logEvent = logEventCaptor.getValue();
assertThat(logEvent.getLevel()).isEqualTo(Level.ERROR);
assertThat(logEvent.getMessage().getFormattedMessage()).contains(expectedErrorMessage);
答案 23 :(得分:0)
使用Jmockit(1.21)我能够编写这个简单的测试。 该测试确保只调用一次特定的ERROR消息。
@Test
public void testErrorMessage() {
final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger( MyConfig.class );
new Expectations(logger) {{
//make sure this error is happens just once.
logger.error( "Something went wrong..." );
times = 1;
}};
new MyTestObject().runSomethingWrong( "aaa" ); //SUT that eventually cause the error in the log.
}
答案 24 :(得分:0)
您无需在类实现中依赖于硬编码的静态全局Logger,可以在默认构造函数中提供默认记录器,然后使用特定的构造函数来设置对所提供记录器的引用。
class MyClassToTest {
private final Logger logger;
public MyClassToTest() {
this(SomeStatic.logger);
};
MyClassToTest(Logger logger) {
this.logger = logger;
};
public void someOperation() {
logger.warn("warning message");
// ...
};
};
class MyClassToTestTest {
@Test
public warnCalled() {
Logger loggerMock = mock(Logger.class);
MyClassTest myClassToTest = new MyClassToTest(logger);
myClassToTest.someOperation();
verify(loggerMock).warn(anyString());
};
}
答案 25 :(得分:0)
就我而言,我解决了与下面相同的问题:
Logger root = (Logger) LoggerFactory.getLogger(CSVTasklet.class); //CSVTasklet is my target class
final Appender mockAppender = mock(Appender.class);
root.addAppender(mockAppender);
verify(mockAppender).doAppend(argThat((ArgumentMatcher) argument -> ((LoggingEvent) argument).getMessage().contains("No projects."))); // I checked "No projects." in the log
答案 26 :(得分:0)
另一个值得一提的想法,虽然它是一个较老的主题,但是创建一个CDI生产者来注入你的记录器,这样就可以轻松地进行模拟。 (而且它还具有不必再声明&#34;整个记录器语句&#34;再次,但那是非主题的)
示例:
创建要注入的记录器:
public class CdiResources {
@Produces @LoggerType
public Logger createLogger(final InjectionPoint ip) {
return Logger.getLogger(ip.getMember().getDeclaringClass());
}
}
限定符:
@Qualifier
@Retention(RetentionPolicy.RUNTIME)
@Target({TYPE, METHOD, FIELD, PARAMETER})
public @interface LoggerType {
}
在生产代码中使用记录器:
public class ProductionCode {
@Inject
@LoggerType
private Logger logger;
public void logSomething() {
logger.info("something");
}
}
在测试代码中测试记录器(给出一个easyMock示例):
@TestSubject
private ProductionCode productionCode = new ProductionCode();
@Mock
private Logger logger;
@Test
public void testTheLogger() {
logger.info("something");
replayAll();
productionCode.logSomething();
}
答案 27 :(得分:-1)
如果您使用的是log4j2,则https://www.dontpanicblog.co.uk/2018/04/29/test-log4j2-with-junit/的解决方案允许我断言已记录了消息。
解决方案如下:
将log4j附加程序定义为ExternalResource规则
public class LogAppenderResource extends ExternalResource {
private static final String APPENDER_NAME = "log4jRuleAppender";
/**
* Logged messages contains level and message only.
* This allows us to test that level and message are set.
*/
private static final String PATTERN = "%-5level %msg";
private Logger logger;
private Appender appender;
private final CharArrayWriter outContent = new CharArrayWriter();
public LogAppenderResource(org.apache.logging.log4j.Logger logger) {
this.logger = (org.apache.logging.log4j.core.Logger)logger;
}
@Override
protected void before() {
StringLayout layout = PatternLayout.newBuilder().withPattern(PATTERN).build();
appender = WriterAppender.newBuilder()
.setTarget(outContent)
.setLayout(layout)
.setName(APPENDER_NAME).build();
appender.start();
logger.addAppender(appender);
}
@Override
protected void after() {
logger.removeAppender(appender);
}
public String getOutput() {
return outContent.toString();
}
}
定义使用您的ExternalResource规则的测试
public class LoggingTextListenerTest {
@Rule public LogAppenderResource appender = new LogAppenderResource(LogManager.getLogger(LoggingTextListener.class));
private LoggingTextListener listener = new LoggingTextListener(); // Class under test
@Test
public void startedEvent_isLogged() {
listener.started();
assertThat(appender.getOutput(), containsString("started"));
}
}
别忘了将log4j2.xml作为src / test / resources的一部分