JUNIT COOKBOOK
来源:互联网 发布:python算法 编辑:程序博客网 时间:2024/05/21 15:47
When you need to test something, here is what you do:
- Annotate a method with @org.junit.Test
- 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
@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:
- Add a field for each part of the fixture
- Annotate a method with @org.junit.Before and initialize the variables in that method
- 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:
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);
@Test(expected= IndexOutOfBoundsException.class) public void empty() { new ArrayList<Object>().get(0); }
- JUnit Cookbook
- JUnit Cookbook
- JUnit Cookbook
- JUNIT COOKBOOK
- [java]JUnit Cookbook
- Cookbook
- cookbook
- JUNIT
- junit
- Junit
- JUnit
- JUnit
- JUnit
- JUNIT
- junit
- Junit
- JUnit
- Junit
- android 语音识别
- 第十一周实验报告(2)
- app内跳转至app store
- 关于扑克
- Qt笔记之绘图QPainterpath
- JUNIT COOKBOOK
- android MediaPlayer播放InputStream解决方案
- SQL Server 2005 中的分区表和索引
- usb鼠标驱动注解及测试收藏
- Linux(centos)编译安装boost
- Python:列表函数
- 以太网芯片MAC和PHY的关系
- linux2.4下DMA的使用
- SQL Server2008存储结构之堆表、行溢出 、页结构、记录结构