Tworzymy klasę w /src/test/java/pakiet
import org.apache.log4j.AppenderSkeleton;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.log4j.spi.LoggingEvent;
import java.util.ArrayList;
import java.util.List;
public class LogsHistorySaver extends AppenderSkeleton {
private List logs;
public void setUp() {
logs = new ArrayList<>();
Logger.getRootLogger().addAppender(this);
}
public void tearDown() {
Logger.getRootLogger().removeAppender(this);
}
public List getLogs() {
return logs;
}
@Override
protected void append(LoggingEvent event) {
logs.add(new Event(event.getLevel(), String.valueOf(event.getMessage())));
}
@Override
public void close() {
}
@Override
public boolean requiresLayout() {
return false;
}
public class Event {
private Level level;
private String message;
Event(Level level, String message) {
this.level = level;
this.message = message;
}
public Level getLevel() {
return level;
}
public String getMessage() {
return message;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("Event{");
sb.append("level=").append(level);
sb.append(", message='").append(message).append('\'');
sb.append('}');
return sb.toString();
}
}
}
I korzystamy w niej w teście w spoób następujący:
public class KaboomTest {
private Kaboom sut;
private LogsHistorySaver logsHistorySaver = new LogsHistorySaver();
@Before
public void setUp() throws Exception {
logsHistorySaver.setUp();
}
@Test
public void log() throws Exception {
//when
sut.build();
//then
List logs = logsHistorySaver.getLogs();
assertThat(logs.size()).isEqualTo(3);
assertThat(logs.get(0).getLevel()).isEqualTo(Level.INFO);
assertThat(logs.get(0).getMessage()).isEqualTo("First log");
assertThat(logs.get(1).getLevel()).isEqualTo(Level.INFO);
assertThat(logs.get(1).getMessage()).isEqualTo("Second log");
assertThat(logs.get(2).getLevel()).isEqualTo(Level.INFO);
assertThat(logs.get(2).getMessage()).isEqualTo("Third log");
}
}
This code looks very familiar ;-)
OdpowiedzUsuńIf this code belongs to You, I am very sorry - I can add your source if You want.
OdpowiedzUsuń