-
Terminology
- Unit test
- Integration test
- System test / functional test
- Regression test
- Continuous integration
- Diff
-
What
- ..tests if individual units of source code are fit for use
- Advantage
-
Should be
- Small/Be fast
- Trustworthiness
- Specific
- Consistent
-
Fully automated
- Only two possible results: Pass or Fail
- No partially successful tests
- A test fails -> The whole suite fails
- Broken window effect
- Single responsibility
- Tests isolation
-
Environment isolation
-
Under unit testing: It doesn't work!
- DB
- Time
- Web service
-
Solution: Use fake
- Fast
- Easy to write
- Easy to re-use
- No test logic in production code
- Self-descriptive
- Code coverage
-
UT Framework
- NUnit
- MbUnit
- MS Unit
-
Why
-
Why have
unit tests?
- Find bugs early / fast feedback
- Increase QA
- Make architecture better
- CostOfWritingUnitTests < Sum(BugFixing)
- 测试代码是功能代码的一个用户,考验系统可扩展性
- 有助于为每个class定义需求
- 详尽的测试套件(test suite)是强大而重要的文档
- 有效的回归测试
- 使重构变得有保障
-
Why not
- Increases development time
- 现在架构不方便作UT
- 知识体系达不到
- 迫于项目进度要求
-
How
-
Web UI
- Selenium
-
Business Logic
- Unit tests
-
Looks like
- Arrange
- Act
- Assert
-
+2
- Set up
- Tear down
-
提高可测试性的技巧
- 针对接口编程,而非针对类编程
- 使用Strategy模式
- 迪米特法则:对象只应该调用自己触手可及的对象。
- 确保每个对象有合理的责任集
- IoC
- AOP
-
Fake
-
When need?
- 真实对象不存在或不完备
- 真实对象本身不确定
- 数据源不稳定
- 代码依赖
- Stub
- Mock
-
Mock
Framework
- Moq
- Rnial
- Mols
-
Advanced
- 可以用简单易行的方法定义模拟对象,无需破坏本来的代码结构表
- 可以定义对象之间的交互,从而增强测试的稳定性
- 可以集成到测试框架
- 易扩充
- Connection and distinction
-
Best practices
- 观念:除了可运行的代码,测试套件比其他任何东西都重要
小步前进:反对一次性编写一大堆测试套件;应测试一点,实现一点。
首先编写独立于代码的测试
在修正某个bug前,先编写一个单元测试,来表现这个bug
即使编写依赖于J2EE API的代码,也应确保它能脱离应用服务器进行单元测试。
- 把任何代码提交到CVS前,完整的运行测试套件
测试的名字要有意义
不要依赖于测试用例的先后顺序
如果用到了配置文件,从classpath来加载。
在IDE中运行单独的测试。
编写ANT脚本来运行所有测试,以及进行测试覆盖率分析
- 使用模仿对象来避免对外部资源的依赖
在必要的时候重构测试代码。
未实现的方法,让其抛出异常。
每个测试(JUNIT测试方法)只测试一件事情。
要保证测试代码的简单性,如果测试代码本身就很复杂,就会导致测试代码本身可能也有Defect。
另一方面,如果测试代码很复杂,往往说明被测试代码的设计不合理,接口不清晰,需要重新设计或是Refactory。
-
Reference
- The Art of Unit Testing with Roy Osherove
- Pragmatic.Bookshelf.Pragmatic.Unit.Testing.in.C.Sharp.with.NUnit.2nd.Edition.Aug.2007
- Manning - The.Art.of.Unit.Testing.with.Examples.in.dot.NET.Jun.2009
- Fowler Martin. "Mocks aren't Stubs"