This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import static org.junit.Assert.*; | |
import static org.hamcrest.CoreMatchers.*; | |
import java.util.Stack; | |
import org.junit.Before; | |
import org.junit.Rule; | |
import org.junit.Test; | |
import org.junit.rules.MethodRule; | |
import org.junit.rules.TestWatchman; | |
import org.junit.runners.model.FrameworkMethod; | |
import org.slf4j.Logger; | |
import org.slf4j.LoggerFactory; | |
public class SampleStackTest { | |
static final Logger logger = | |
LoggerFactory.getLogger(SampleStackTest.class); | |
@Rule public MethodRule watchman = new TestWatchman() { | |
public void starting(FrameworkMethod method) { | |
logger.info("Run Test {}...", method.getName()); | |
} | |
public void succeeded(FrameworkMethod method) { | |
logger.info("Test {} succeeded.", method.getName()); | |
} | |
public void failed(Throwable e, FrameworkMethod method) { | |
logger.error("Test {} failed with {}.", method.getName(), e); | |
} | |
}; | |
Stack<String> stack; | |
@Before public void createEmptyStack() { | |
stack = new Stack<String>(); | |
} | |
// the sample test demonstrate logging of a succeeded test. | |
@Test public void pushOneElementInEmptyStack() { | |
stack.push("Item One"); | |
assertThat(stack.size(), is(1)); | |
} | |
// the sample test demonstrate logging of a failed test | |
// with an EmptyStackException | |
@Test public void popElementFromEmptyStack() { | |
stack.pop(); | |
assertThat(stack.size(), is(0)); | |
} | |
// the sample test demonstrate logging of a failed test | |
// with an AssertionError | |
@Test public void sizeEmptyStack() { | |
assertThat(stack.size(), is(1)); | |
} | |
} |
For more details about logging in JUnit tests see the blog post "JUnit 4 Test Logging Tips using SLF4J".