浅谈单元测试关注的一些点

来源:互联网 发布:阿里旺旺软件下载网页 编辑:程序博客网 时间:2024/05/16 17:33
1、每次只测试一个代码单元(方法);
2、确保在内存中运行单元测试;
3、模拟所有外部服务和状态;
4、使用最合适的断言方法;
有许多断言 assertEquals,assertTrue,assertFalse,assertNull,assertNotNull,assertArrayEquals,assertSame 使用最合适的一个最可读的测试代码。 例如:使用 assertTrue(result) 而不是 assertEquals(true,result)使用 assertEquals(expected,actual) 而不是 assertTrue(actual.equals(expected))使用 assertEquals(expectedCollection, actualCollection) 而不是声明集合的大小和每个集合的成员
5、清楚、一致的命名;
例如1) testCreateEmployee_NullId_ShouldThrowException2) testCreateEmployee_NegativeId_ShouldThrowException3) testCreateEmployee_DuplicateId_ShouldThrowException4) testCreateEmployee_ValidId_ShouldPass
6、注意断言参数的顺序;
assertEquals(预期值,实际值)
7、直接测试类,不要间接测试;
8、不要在单元测试类构造函数初始化;
9、创建针对异常的单元测试、无需编写自己的catch块;
测试方法 抛出Exception 而不是抛出详细的如IOException代替手动抓预期的异常,使用预期的属性 @Test 注释@Test(expected = IOException.class)public void test() throws Exception{  //}
10、每个单元测试争取一个断言;





原创粉丝点击