我正在测试一种方法,当出现问题时记录警告并返回null 类似的东西:
private static final Logger log = Logger.getLogger(Clazz.class.getName());
....
if (file == null || !file.exists()) {
// if File not found
log.warn("File not found: "+file.toString());
} else if (!file.canWrite()) {
// if file is read only
log.warn("File is read-only: "+file.toString());
} else {
// all checks passed, can return an working file.
return file;
}
return null;
我想用junit测试是否发出警告,除了返回null之外,在所有情况下(例如找不到文件,文件是只读的)。
任何想法?
谢谢,asaf: - )
我对亚伦答案的实施(加上彼得的评论):
public class UnitTest {
...
@BeforeClass
public static void setUpOnce() {
appenders = new Vector<Appender>(2);
// 1. just a printout appender:
appenders.add(new ConsoleAppender(new PatternLayout("%d [%t] %-5p %c - %m%n")));
// 2. the appender to test against:
writer = new StringWriter();
appenders.add(new WriterAppender(new PatternLayout("%p, %m%n"),writer));
}
@Before
public void setUp() {
// Unit Under Test:
unit = new TestUnit();
// setting test appenders:
for (Appender appender : appenders) {
TestUnit.log.addAppender(appender);
}
// saving additivity and turning it off:
additivity = TestUnit.log.getAdditivity();
TestUnit.log.setAdditivity(false);
}
@After
public void tearDown() {
unit = null;
for (Appender appender : appenders) {
TestUnit.log.removeAppender(appender);
}
TestUnit.log.setAdditivity(additivity);
}
@Test
public void testGetFile() {
// start fresh:
File file;
writer.getBuffer().setLength(0);
// 1. test null file:
System.out.println(" 1. test null file.");
file = unit.getFile(null);
assertNull(file);
assertTrue(writer.toString(), writer.toString().startsWith("WARN, File not found"));
writer.getBuffer().setLength(0);
// 2. test empty file:
System.out.println(" 2. test empty file.");
file = unit.getFile("");
assertNull(file);
assertTrue(writer.toString(), writer.toString().startsWith("WARN, File not found"));
writer.getBuffer().setLength(0);
}
谢谢你们,
答案 0 :(得分:37)
在单元测试的设置中:
添加一个记住列表中消息的appender:
public class TestAppender extends AppenderSkeleton {
public List<String> messages = new ArrayList<String>();
public void doAppend(LoggingEvent event) {
messages.add( event.getMessage().toString() );
}
}
将appender添加到记录器
现在您可以调用您的代码了。测试后,您将在列表中找到所有日志消息。如果需要,可以添加日志级别(messages.add( event.getLevel() + " " + event.getMessage() );
)。
在tearDown()
中,再次删除appender并启用可加性。
答案 1 :(得分:14)
使用Mockito,您可以使用最少的样板代码测试测试期间发生的记录,一个简单的例子是:
@RunWith(MockitoJUnitRunner.class)
public class TestLogging {
@Mock AppenderSkeleton appender;
@Captor ArgumentCaptor<LoggingEvent> logCaptor;
@Test
public void test() {
Logger.getRootLogger().addAppender(appender);
...<your test code here>...
verify(appender).doAppend(logCaptor.capture());
assertEquals("Warning message should have been logged", "Caution!", logCaptor.getValue().getRenderedMessage());
}
}
答案 2 :(得分:8)
这篇文章中的例子非常有用,但我发现它们有点令人困惑
所以我在上面添加了一个简化版本,稍作修改。
这种方式,默认情况下假设加法为真,我不需要担心由于记录器层次结构而丢失我的事件。确保这符合您的log4j.properties文件配置。
在AppenderSkeleton中附加处理级别过滤,所以我不想错过。
如果级别正确,doAppend将调用append。
public class TestLogger {
@Test
public void test() {
TestAppender testAppender = new TestAppender();
Logger.getRootLogger().addAppender(testAppender);
ClassUnderTest.logMessage();
LoggingEvent 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");
}
public static class TestAppender extends AppenderSkeleton{
public List<LoggingEvent> events = new ArrayList<LoggingEvent>();
public void close() {}
public boolean requiresLayout() {return false;}
@Override
protected void append(LoggingEvent event) {
events.add(event);
}
}
public static class ClassUnderTest {
private static final Logger LOGGER =
Logger.getLogger(ClassUnderTest.class);
public static void logMessage(){
LOGGER.info("Hello Test");
LOGGER.debug("Hello Test");
}
}
}
log4j.properties
log4j.rootCategory=INFO, CONSOLE
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=%d %p [%c] - %m%n
# un-comment this will fail the test
#log4j.logger.com.haim.logging=DEBUG
答案 3 :(得分:7)
Aaron解决方案的替代方案是配置WriterAppender并附加StringWriter。在测试结束时,您可以验证日志输出字符串的内容。
这更容易实现(不需要自定义代码),但是在检查结果方面不太灵活,因为您只能将输出作为纯文本。在某些情况下,可能会比使用Aaron的解决方案更难以验证输出。
答案 4 :(得分:2)
不要直接调用log4j,而是在类中使用受保护的方法。
类似的东西:
protected void log(String message, Level level)
{
//delegates to log4j
}
然后创建一个正在测试的类的子类,该类的子类使用该方法,以便您可以验证它是否按预期调用。
class MyTest extends <class under test>
{
boolean somethingLogged = false;
protected void log(String message, Level level)
{
somethingLogged = true;
}
}
然后根据somethingLogged断言。您可以根据预期的消息/级别在覆盖方法t test中添加条件逻辑。
您可以更进一步记录所有调用,然后搜索记录的消息,或检查它们是否以正确的顺序登录等等。
答案 5 :(得分:1)
我正在调整Haim对更多RAII的回答:
public static class TestAppender extends AppenderSkeleton {
@Override
protected void append(LoggingEvent event) {
messages.add(event.getRenderedMessage());
}
@Override
public void close() { }
@Override
public boolean requiresLayout() { return false; }
protected final List<String> messages = new ArrayList<>();
}
static class LogGuard implements AutoCloseable {
protected final TestAppender appender;
LogGuard(Level level) {
appender = new TestAppender();
appender.setThreshold(level);
Logger.getRootLogger().addAppender(appender);
}
@Override
public void close() throws Exception {
Logger.getRootLogger().removeAppender(appender);
}
}
然后用法很简单:
try (LogGuard log = new LogGuard(Level.WARN)) { // if you want WARN or higher
// do what causes the logging
Assert.assertTrue(log.appender.messages.stream().anyMatch(m -> m.equals("expected"));
}