1.先说说什么是单元测试吧?
写了类,要给别人用的,要先检查一下该代码中有没有bug
用main方法不好用,不能执行多个测试方法。就算能运行也比较难观察。而且测试也不能在重用。
2.junit
new project
建立类
建立testcase
放弃旧的断言,使用hamcrest断言
1.asserThat
2.使用hamcrest的匹配方法
(1)更自然
3.实例
(2)
assertThat(n,allOf(greaterThan(1),lessTham(15)));
assertThat(n,anyOf(greaterThan(16),lessTham(8)));
assertThat(n,anyting());
assertThat(str,is("xxxx"));
assertThat(str,not("xxx"));
(3)assertThat(str,containsString("xxx"));
assertThat(str,endsWith("xxx"));
assertThat(str,startsWith("xxx"));
assertThat(n,equalTo("nExpected"));
assertThat(str,equalToIgnoringCase("xxx"));
assertThat(str,equalToIgnoringWhiteSpace("xxx"));
(4)assertThat(d,closeTo(3.0,0.3));
assertThat(d,greaterThan(3.0));
assertThat(d,lessThan(10.0));
assertThat(d,greaterThanOrEqualTo(5.0));
assertThat(d,lessThanOrEqualTo(16.0));
(5)assertThat(map,hasEntry("xxx","xxx"));
assertThat(iterable,hasItem("xxx"));
assertThat(map,hasKty("xxx"));
assertThat(map,hasValue("xxx"));
Faliure 和 Error
1.Falure是指测试失败
2.Error是指测试程序本身出错
JUnit4 Annotation
1. @Test:测试方法
(1)(expected=XXEception.class)
(2)(timeout=xxx)
2.@Ignore:被忽略的测试方法
3.@Before:每一个测试方法之后运行
4.@After:每一次测试方法之后运行
5.@BeforeClass:所有测试开始之前运行
6.@AfterClass:所有测试结束之后运行
运行多个测试
注意
1.遵守约定,比如:
(1)类纺织test包中
(2)类名用XXXTest结尾
(3)方法用testMethod命名
[url]https://github.com/KentBeck/junit/downloads[/url] junit下载
[url]http://code.google.com/p/hamcrest/downloads/list[/url] hamcrest下载
写了类,要给别人用的,要先检查一下该代码中有没有bug
用main方法不好用,不能执行多个测试方法。就算能运行也比较难观察。而且测试也不能在重用。
2.junit
new project
建立类
建立testcase
放弃旧的断言,使用hamcrest断言
1.asserThat
2.使用hamcrest的匹配方法
(1)更自然
3.实例
(2)
assertThat(n,allOf(greaterThan(1),lessTham(15)));
assertThat(n,anyOf(greaterThan(16),lessTham(8)));
assertThat(n,anyting());
assertThat(str,is("xxxx"));
assertThat(str,not("xxx"));
(3)assertThat(str,containsString("xxx"));
assertThat(str,endsWith("xxx"));
assertThat(str,startsWith("xxx"));
assertThat(n,equalTo("nExpected"));
assertThat(str,equalToIgnoringCase("xxx"));
assertThat(str,equalToIgnoringWhiteSpace("xxx"));
(4)assertThat(d,closeTo(3.0,0.3));
assertThat(d,greaterThan(3.0));
assertThat(d,lessThan(10.0));
assertThat(d,greaterThanOrEqualTo(5.0));
assertThat(d,lessThanOrEqualTo(16.0));
(5)assertThat(map,hasEntry("xxx","xxx"));
assertThat(iterable,hasItem("xxx"));
assertThat(map,hasKty("xxx"));
assertThat(map,hasValue("xxx"));
Faliure 和 Error
1.Falure是指测试失败
2.Error是指测试程序本身出错
JUnit4 Annotation
1. @Test:测试方法
(1)(expected=XXEception.class)
(2)(timeout=xxx)
2.@Ignore:被忽略的测试方法
3.@Before:每一个测试方法之后运行
4.@After:每一次测试方法之后运行
5.@BeforeClass:所有测试开始之前运行
6.@AfterClass:所有测试结束之后运行
运行多个测试
注意
1.遵守约定,比如:
(1)类纺织test包中
(2)类名用XXXTest结尾
(3)方法用testMethod命名
[url]https://github.com/KentBeck/junit/downloads[/url] junit下载
[url]http://code.google.com/p/hamcrest/downloads/list[/url] hamcrest下载