By Katarina Hallberg
Since version 4.7, 2009
public class SettingsTest {
@Rule
public TemporaryFolder folder = new TemporaryFolder();
@Test
public void setting_can_be_retrieved_by_key() throws IOException {
File properties = folder.newFile("test.properties");
BufferedWriter out =
new BufferedWriter(new FileWriter(properties));
out.write("name = Katarina\n");
out.close();
Settings settings = new Settings();
settings.load(properties);
assertEquals("Katarina", settings.get("name"));
}
}
public class TestClass {
@Test
public void test_one() {...}
@Test
public void test_two() {...}
@Test
public void test_three() {...}
}
public abstract class Statement {
public abstract void evaluate() throws Throwable;
}
public interface TestRule {
Statement apply(Statement base, Description description);
}
public class SuperTestUsingRules {
@Rule
public LoggingRule loggingRule = new LoggingRule();
@Test
public void test_one() {...}
@Test
public void test_two() {...}
}
public class SuperTestUsingRules {
@ClassRule
public static LoggingRule loggingRule = new LoggingRule();
@Test
public void test_one() {...}
@Test
public void test_two() {...}
}
public class LoggingRule implements TestRule {
@Override
public Statement apply(Statement base, Description description) {
return new Statement() {
@Override
public void evaluate() throws Throwable {
System.out.println("Before executing original Statement");
try {
base.evaluate();
} finally {
System.out.println("After executing original Statement");
}
}
};
}
}
public class ExpectedExceptionTest {
@Rule
public ExpectedException thrown = ExpectedException.none();
@Test
public void throws_nullpointer_exception() {
thrown.expect(NullPointerException.class);
thrown.expectMessage(endsWith("null pointer"));
throwNullPointerException();
}
private void throwNullPointerException() {
throw new NullPointerException("This is a null pointer");
}
}
public class LoggingRule implements TestRule {
@Override
public Statement apply(Statement base, Description description) {
return new Statement() {
@Override
public void evaluate() throws Throwable {
System.out.println("Before executing original Statement");
try {
base.evaluate();
} finally {
System.out.println("After executing original Statement");
}
}
};
}
}
public class LoggingRule extends ExternalResource {
@Override
protected void before() throws Throwable {
System.out.println("Before executing original Statement");
}
@Override
protected void after() {
System.out.println("After executing original Statement");
}
}
(Demo)