标签:junit4 测试 教程 单元测试 测试
Junit 4 断言方法允许检查测试方法的期望结果值和真实返回值。Junit的org.junit.Assert类提供了各种断言方法来写junit测试。这些方法被用来检查方法的真实结果值和期望值。下列一些有用的断言方法列表:
Method | Description |
---|---|
assertNull(java.lang.Object object) | 检查对象是否为空 |
assertNotNull(java.lang.Object object) | 检查对象是否不为空 |
assertEquals(long expected, long actual) | 检查long类型的值是否相等 |
assertEquals(double expected, double actual, double delta) | 检查指定精度的double值是否相等 |
assertFalse(boolean condition) | 检查条件是否为假 |
assertTrue(boolean condition) | 检查条件是否为真 |
assertSame(java.lang.Object expected, java.lang.Object actual) | 检查两个对象引用是否引用同一对象(即对象是否相等) |
assertNotSame(java.lang.Object unexpected, java.lang.Object actual) |
检查两个对象引用是否不引用统一对象(即对象不等) |
AssertionsTest.java junit测试用例,显示各种断言方法:
import static org.junit.Assert.*; import java.util.ArrayList; import java.util.List; import org.junit.Test; /** * @author javatutorials.co.in */ public class AssertionsTest { @Test public void testAssertNull() { String str = null; assertNull(str); } @Test public void testAssertNotNull() { String str = "hello Java!!"; assertNotNull(str); } @Test public void testAssertEqualsLong() { long long1 = 2; long long2 = 2; assertEquals(long1, long2); } @Test public void testAssertEqualsDouble() { // test case is successfull as double1 and double 2 // differ by 0.001 which is less than our specified delta double double1 = 1.236; double double2 = 1.237; double delta = 0.002; assertEquals(double1, double2, delta); } @Test public void testAssertTrue() { List<String> list = new ArrayList<String>(); assertTrue(list.isEmpty()); } @Test public void testAssertFalse() { List<String> list = new ArrayList<String>(); list.add("hello"); assertFalse(list.isEmpty()); } @Test public void testAssertSame() { String str1 = "hello world!!"; String str2 = "hello world!!"; assertSame(str2, str1); } @Test public void testAssertNotSame() { String str1 = "hello world!!"; String str3 = "hello Java!!"; assertNotSame(str1, str3); } }
样例输出在eclipse Junit 窗口的输出如下:
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Junit 4 Tutorials(Junit 4 教程) 三、Junit4 断言方法,布布扣,bubuko.com
Junit 4 Tutorials(Junit 4 教程) 三、Junit4 断言方法
标签:junit4 测试 教程 单元测试 测试
原文地址:http://blog.csdn.net/luanlouis/article/details/37562777