一、前言
1、什么是单元测试写了个类,要给别人用,会不会有bug?怎么办?测试一下。
你的类库给别人调用但最后的结果是错的,是你的错还是他的错?最好确定你的方法是正确的
用main方法测试好不好?不好!
1)不能一起运行!
2)大多数情况下需要人为的观察输出确定是否正确
二、为什么要进行单元测试
1、重用测试,应付将来的实现的变化2、提高士气,明确知道我的东西是没问题的
3、降低后期维护花费的成本和人力
4、测试人员测的是整个系统功能正常不正常,性能达不达到设计要求。但是不能测一个方法,一个接口
三、JUnit4 HelloWorld
1、new project1)eclipse包含JUnit包,new - JUnit Test Case
2、建立类
3、建立testcase
1)import static org.junit.Assert.*;
静态引入,就是引入这个类的所有静态方法
2)assert意思是断言,就是判断
assertEquals(expected, actual); 判断期望值和实际值是不是相等,如果相等就算你通过
3)keeps the bar green to keeps the code clean
四、放弃旧的断言,使用hamcrest断言
1、assertThatassertThat替代了其他所有的assert方法
2、使用hamcrest的匹配方法
1)引入jar包:
hamcrest-library-1.3.jar
hamcrest-all-1.3.jar
import static org.hamcrest.Matchers.*;
2)如果报安全错误:
java.lang.SecurityException: class "org.hamcrest.Matchers"'s signer information does not match signer information of other classes in the same package
因为JUnit的包和hamcrest的包ClassLoader用的不是同一个,解决办法是不用eclipse自带的JUnit包,自己引入JUnit。
3)更自然
3、示例
assertThat(8, is(1));
五、Failure和Error
1、Failure是指测试失败2、Error是指测试程序本身出错
六、JUnit4 Annotation
1、@Test:测试方法1)(expected=XXException.class)
2)(timeout=xxx)
2、@Ignore:被忽略的测试方法
3、@Before:每一个测试方法之前运行
4、@After:每一个测试方法之后运行
5、@BeforeClass:所有测试开始之前运行,必须是static,在类加载之前运行
6、@AfterClass:所有测试结束之后运行,必须是static,在类加载之前运行
七、注意
1、遵守约定,比如:1)类放在test包中
2)类名用XXXTest结尾
3)方法用testXXXMethod命名
八、Junit其他用途
1、Junit测试servlet2、easy mock测试mock对象
3、测试spring、struts、hibernate
马士兵语录:
豆芽张一房高,它还是根菜