您的位置:首页 > 其它

[1]Junit4-Assertions的使用

2016-08-31 22:54 363 查看
官网:http://junit.org/junit4/

想要减少程序的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,更何况是简单的测试?一行代码出错就是错,不要小看每一行代码。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  junit