查看文章 |
JUnit Cook Book
2008-11-27 14:19
JUnit CookbookKent Beck, Erich Gamma Simple Test CaseWhen you need to test something, here is what you do:
If you want to write a test similar to one you have already written, write a Fixture instead.
FixtureWhat if you have two or more tests that operate on the same or similar sets of objects? This set of objects is called a test fixture.When you have a common fixture, here is what you do:
public class MoneyTest {
private Money f12CHF;
private Money f14CHF;
private Money f28USD;
@Before public void setUp() {
f12CHF= new Money(12, "CHF");
f14CHF= new Money(14, "CHF");
f28USD= new Money(28, "USD");
}
}
Running Testsrun this from a Java program:
or this from the command line, with both your test class and junit on the classpath:org.junit.runner.JUnitCore.runClasses(TestClass1.class, ...); java org.junit.runner.JUnitCore TestClass1.class [...other test classes...]
You make your JUnit 4 test classes accessible to a TestRunner designed to work with earlier versions of JUnit, declare a static method suite that returns a test.
Expected ExceptionsMaking sure the code behaves as expected in exceptional situations is part of the craft of programming too. For example: This code should throw an IndexOutOfBoundsException. The @Test annotation has an optional parameter "expected" that takes as values subclasses of Throwable. If we wanted to verify that ArrayList throws the correct exception, we would write:new ArrayList<Object>().get(0);
|
最近读者: