[1]Junit4-Assertions的使用
2016-08-31 22:54
363 查看
官网:http://junit.org/junit4/
想要减少程序的Bug?
Junit的作用就是一个测试代码工具,使用它我们可以很简单地进行测试驱动开发,减少代码Bug。
maven配置:
Assertion的作用:Assertion包含各种方法,方法格式类似assertXXX方法,可以比较对象、基本数据类型和数组是否相等或不等或是否包含指定内容等。
看完以上代码是否觉得简单,觉得可有可无?有时候我们程序的Bug是因为我们的大意和太过自信,没在实际环境运行过的代码我们不能100%保证无Bug,更何况是简单的测试?一行代码出错就是错,不要小看每一行代码。
想要减少程序的Bug?
Junit的作用就是一个测试代码工具,使用它我们可以很简单地进行测试驱动开发,减少代码Bug。
maven配置:
<dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency>
Assertion的作用:Assertion包含各种方法,方法格式类似assertXXX方法,可以比较对象、基本数据类型和数组是否相等或不等或是否包含指定内容等。
package com.mjj.test; import org.hamcrest.CoreMatchers; import org.junit.Test; import java.util.Arrays; import static org.junit.Assert.*; public class TestAssertions { @Test public void testAssertArrayEquals(){ int [] expected=new int[2]; expected[0]=1; expected[1]=2; int [] actual=new int [2]; actual[0]=1; actual[1]=2; //数组内容必须一致 assertArrayEquals("array must equals",expected,actual); Object[] expectedObjArray=new Object[1]; expectedObjArray[0]=new java.lang.Object(); Object[] actualObjArray=new Object[1]; actualObjArray[0]=new java.lang.Object(); //数组内容必须一致,对象验证必须是同一个对象 assertArrayEquals("array must equals,Object must be same",expectedObjArray,actualObjArray); } @Test public void testAssertEquals(){ assertEquals("string must be equals:","s","s"); } @Test public void testAssertNotNull(){ assertNotNull("object must not null",null); } @Test public void testAssertNull(){ assertNull("object must null", new Object()); } @Test public void testAssertNotSame(){ assertNotSame("value should not be same","s","s"); } @Test public void textAssertSame(){ assertSame("value should be same",new Object(),new Object()); } @Test public void testAssertBooleanEquals(){ assertFalse("should be false", true); } @Test public void testAssertThatBothContainsString(){ //Matchers匹配模式,功能比较强大 assertThat("albumen", CoreMatchers.both(CoreMatchers.containsString("a")).and(CoreMatchers.containsString("n"))); } @Test public void testAssertThatHasItems(){ //验证list是否包含元素 assertThat(Arrays.asList("one","two","three"),CoreMatchers.hasItems("two","one")); } }
看完以上代码是否觉得简单,觉得可有可无?有时候我们程序的Bug是因为我们的大意和太过自信,没在实际环境运行过的代码我们不能100%保证无Bug,更何况是简单的测试?一行代码出错就是错,不要小看每一行代码。
相关文章推荐
- 在Eclipse中使用JUnit进行单元测试
- 如何使用Junit编写和组织测试程序
- JbuilderX使用Junit学习笔记
- junit的使用
- Eclipse中JUnit使用基础
- 使用Junit时源代码和测试代码的组织(摘自Daping_Zhang 的 Blog )
- junit使用简明手册
- Eclipse学习4-在Eclipse中使用JUnit进行单元测试(下)
- JUnit的使用
- 使用ant编译、运行junit、以及检查编码
- 利用 Ant 和 JUnit 进行增量开发-使用单元测试来逐步改进代码
- 使用ant编译、运行junit、以及检查编码
- JbuilderX使用Junit学习笔记
- 在Eclipse中使用JUnit
- junit使用简明手册
- 在Eclipse中使用JUnit(翻译)
- JUnit的框架设计及其使用的设计模式
- 在Eclipse中使用JUnit(翻译)
- 单元测试之道 -使用JUnit
- JUNIT使用心得