您的位置:首页 > 其它

junit搭配hamcrest使用

2017-10-07 17:13 232 查看

开篇
- 快速进行软件编码,与功能测试应该是每个写代码的人,应该掌握的技能,如何进行优雅的写代码,把测试的时间压缩,腾出时间来休息。下面听我一一道来:

依赖:junit 4.4
hamcrest 1.3 core hamcrest 1.3 lib
——包我会放到码云

  • 项目结构

  • 选择测试类,创建测试用例: test case

  • 勾选需要测试的方法


- 下一步生成测试用例

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;

import java.io.ByteArrayOutputStream;
import java.io.PrintStream;

import static org.hamcrest.Matchers.*;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

public class DateTest2 {
private Date allDate;
private ByteArrayOutputStream bytes;
@Before
public void setUp() throws Exception {
allDate=new Date(5, 18, 2017);
bytes = new ByteArrayOutputStream();
System.setOut(new PrintStream(bytes));
}

@After
public void tearDown() throws Exception {
System.setOut(System.out);
}

@Test
public void testDate() {
Date date=new Date(5, 18, 2017);
assertEquals(true, date instanceof Date);
}

@Test
public void testIncrement() {
allDate.increment();
System.out.println();
assertEquals(6, allDate.getMonth().getMonth());
}
@Test
public void testPrintDate() {
allDate.printDate();
assertThat(bytes.toString(),is("5/18/2017\r\n"));
}

@Test
public void testGetDay() {
fail("Not yet implemented");
}

@Test
public void testGetMonth() {
fail("Not yet implemented");
}

@Test
public void testGetYear() {
fail("Not yet implemented");
}

@Test
public void testEqualsObject() {
fail("Not yet implemented");
}

@Test
public void testToString() {
fail("Not yet implemented");
}

}
  • fail() 方法为测试junit自动生成,意味失败;下面列举junit常用测试方法“

    也叫 断言 使用断言时候 ,建议静态导入

assertEquals(String msg, Object expectRes, Object Res) --------  用于值判断

判断expectRes.equals(Res) ,表示值等于的判断,失败则抛MSG

assertSame(String msg, Object expectRes, Object Res)  --------  用于地址判断

判断expectRes==Res,表示地址等于的判断,失败则抛MSG

assertTrue(String msg,Boolean result) ----------------------------用于Boolean判断

判断result是true还是false,失败则抛MSG

assertNull(String msg,Object result)-------------------------------用于NULL判断

判断result是否为NULL,失败则抛MSG

fail(String msg);---------------------------------------------------直接中止方法运行

直接中止方法运行,抛出MSG
  • 每一个测试方法上@test 为标注为junit测试方法 ;

显示绿条,意味测试通过

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: