百度空间 | 百度首页 
 
查看文章
 
JUnit Cook Book
2008-11-27 14:19

JUnit Cookbook

Kent Beck, Erich Gamma

Simple Test Case

When you need to test something, here is what you do:

  1. Annotate a method with @org.junit.Test
  2. When you want to check a value, import org.junit.Assert.* statically, call assertTrue() and pass a boolean that is true if the test succeeds
For example:
@Test public void simpleAdd() {
      Money m12CHF= new Money(12, "CHF"); 
      Money m14CHF= new Money(14, "CHF"); 
      Money expected= new Money(26, "CHF"); 
      Money result= m12CHF.add(m14CHF); 
      assertTrue(expected.equals(result));
}
If you want to write a test similar to one you have already written, write a Fixture instead.

Fixture

What 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:

  1. Add a field for each part of the fixture
  2. Annotate a method with @org.junit.Before and initialize the variables in that method
  3. Annotate a method with @org.junit.After to release any permanent resources you allocated in setUp
For example:
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 Tests

run this from a Java program:

org.junit.runner.JUnitCore.runClasses(TestClass1.class, ...);
or this from the command line, with both your test class and junit on the classpath:
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.

public static junit.framework.Test suite() { 
      return new JUnit4TestAdapter(Example.class); 
}

Expected Exceptions

Making sure the code behaves as expected in exceptional situations is part of the craft of programming too. For example:

new ArrayList<Object>().get(0); 
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:
@Test(expected= IndexOutOfBoundsException.class) public void empty() { 
      new ArrayList<Object>().get(0); 
}

类别:开发工具 | 添加到搜藏 | 浏览() | 评论 (0)
 
最近读者:
 
网友评论:
发表评论:
姓 名:
网址或邮箱: (选填)
内 容:
验证码: 请点击后输入四位验证码,字母不区分大小写
      

     

©2009 Baidu