JUNIT COOKBOOK

来源:互联网 发布:python算法 编辑:程序博客网 时间:2024/05/21 15:47

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, to test that the sum of two Moneys with the same currency contains a value which is the sum of the values of the two Moneys, write:
@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));}

Fixture (骨架)

What if you have two or more tests that operate on the same or similar sets of objects?

Tests need to run against the background ofa known set 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

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

How do you run your tests and collect their results?

Once you have tests, you'll want to run them. JUnit provides tools to define the suite to be run and to display its results. To run tests and see the resultson the console, 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 [...other test classes...]

Expected Exceptions

How do you verify that code throws exceptions as expected?

 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); }

原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 想辞职领导不批怎么办 急辞职领导不批怎么办 她生气不理我了怎么办 分手了之前的钱怎么办 结婚后老公变了怎么办 我不小心出轨了怎么办 微博账号被锁定怎么办 微博被盗号了怎么办 如果微博被盗了怎么办 老公炒股亏光了怎么办 新id密码不匹配怎么办 手机不识别sd卡怎么办 小米手环容易掉怎么办 小米4gps信号弱怎么办 小米4内存不够用怎么办 地暖放气阀漏水怎么办 暖气排气阀堵了怎么办 跳绳一只脚腕疼怎么办 牙齿不能吃冷的怎么办 牙齿不敢吃凉的怎么办 蛀牙吃凉的就疼怎么办 吃冷的牙齿就痛怎么办 七日杀定居之旅怎么办 眼睛肿好几天了怎么办 下眼睑疼痒肿痛怎么办 整个上眼皮肿了怎么办 上眼皮突然肿了怎么办 眼皮很肿又厚怎么办 上眼皮上长疙瘩怎么办 小孩眼睛长了麦粒肿怎么办 眼睛里长了麦粒肿怎么办 肛周脓肿流脓了怎么办 眼睑肿了一个包怎么办 上眼皮长针眼了怎么办 三岁宝宝内热重怎么办 5个月小孩内火重怎么办 孕妇o型rh阳性怎么办 异次元通讯对方下线了怎么办 人感染朊病毒了怎么办 美图m2忘记密码怎么办 美图m2很卡怎么办