本文主要是介绍Junit 4 Tutorials(Junit 4 教程) 三、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) | 检查两个对象引用是否不引用统一对象(即对象不等) |
Junit 4断言方法样例
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 {@Testpublic void testAssertNull() {String str = null;assertNull(str);}@Testpublic void testAssertNotNull() {String str = "hello Java!!";assertNotNull(str);}@Testpublic void testAssertEqualsLong() {long long1 = 2;long long2 = 2;assertEquals(long1, long2);}@Testpublic void testAssertEqualsDouble() {// test case is successfull as double1 and double 2// differ by 0.001 which is less than our specified deltadouble double1 = 1.236;double double2 = 1.237;double delta = 0.002;assertEquals(double1, double2, delta);}@Testpublic void testAssertTrue() {List<String> list = new ArrayList<String>();assertTrue(list.isEmpty());}@Testpublic void testAssertFalse() {List<String> list = new ArrayList<String>();list.add("hello");assertFalse(list.isEmpty());}@Testpublic void testAssertSame() {String str1 = "hello world!!";String str2 = "hello world!!";assertSame(str2, str1);}@Testpublic void testAssertNotSame() {String str1 = "hello world!!";String str3 = "hello Java!!";assertNotSame(str1, str3);} }
样例输出在eclipse Junit 窗口的输出如下:
源码下载
点击我下载源码
教程目录导航
- Junit测试框架介绍
- Junit Eclipse教程
- Junit 4注解
- Junit 4断言方法(Assert methods)
- Junit 4参数化测试
- Junit 4测试套件(Test Suite)
- Junit 4忽略测试(Ignore Test)
- Junit 4超时测试(Timeout Test)
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
这篇关于Junit 4 Tutorials(Junit 4 教程) 三、Junit4 断言方法的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!