NoWarningsLogChecker.java

package com.ziesemer.utils.junit.logCheck;

import static org.junit.Assert.fail;

import org.junit.runner.Description;

import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.spi.ILoggingEvent;

/**
 * <p>
 * 	Basic {@link ILogChecker} that will throw an {@link AssertionError} during {@link #finalCheck()}
 * 		if there were any warnings or errors reported to {@link #addLogEvent(ILoggingEvent)},
 * 		with separate counts of the errors and warnings reported.
 * </p>
 * @author Mark A. Ziesemer
 * 	<a href="http://www.ziesemer.com.">&lt;www.ziesemer.com&gt;</a>
 */
public class NoWarningsLogChecker implements ILogChecker{
	
	protected int warningCount;
	protected int errorCount;
	
	public void init(final Description description){
		warningCount = 0;
		errorCount = 0;
	}
	
	public void addLogEvent(final ILoggingEvent event){
		if(event.getLevel().isGreaterOrEqual(Level.WARN)){
			if(event.getLevel().isGreaterOrEqual(Level.ERROR)){
				errorCount++;
			}else{
				warningCount++;
			}
		}
	}
	
	public void finalCheck() throws Exception{
		if(warningCount > 0 || errorCount > 0){
			String errors = errorCount + " error";
			if(errorCount != 1){
				errors += "s";
			}
			String warnings = warningCount + " warning";
			if(warningCount != 1){
				warnings += "s";
			}
			fail(errors + " and " + warnings + " were logged.");
		}
	}
	
}