Testing private methods, TDD, and test-driven refactoring

[复制链接]
查看11 | 回复0 | 2007-1-24 12:56:49 | 显示全部楼层 |阅读模式
While being a TDD--Test Driven Development--coach, Paulo Caroli always asked about testing private methods. He finally decided to write about his experience on testing private methods.
When really doing TDD (i.e. writing the test code before writing the functional code, and then refactoring the code) private methods are guaranteed to be test covered. When driving the functional code design and implementation from the unit test (aka Test Driven Development), no method is created private. Instead, the private methods are extracted—extract method refactoring step--from a public or package level method. The Example 1 below presents a scenario on applying TDD and how the private method is created.
New code development following TDD
Example 1: new code development following TDD
Consider the development example following a TDD sequence for creating methodA and methodB.
create testMethodA/ create methodA/ refactoring
create testMethodB/ create methodB/ refactoring: extract methodC
On the first sequence, the testMethodA is created for validating the functionality expected of methodA. The methodA is successfully created: All tests including the testMethodA are passing. Then you look for improvements in the code; refactoring.
On the second sequence, the testMethodB is created for validating the functionality expected of methodB. The methodB is successfully created. All tests including the testMethodB are passing. Then you look for improvements in the code; refactoring.
While looking for improvements in the TDD Refactoring step, you recognize that methodA and methodB have a common fragment of code (code duplication). You extract the common code fragment into a private method whose name explains the purpose of the method--methodC. Then methodA and methodB invoke methodC.
In this example testMethodA covers methodA, which invokes private methodC; therefore the private methodC is test covered.
Please keep in mind that this is a simplified example. Your methods and tests should not read like testMethodA / methodA, and testMethodB / methodB. Jeff Patton describes how test cases can describe design in his Test-Driven Development Isn’t Testing paper.
When doing TDD, the private methods emerge from your code. And because you test-drive your development, no functionality is added without a test. So, for code fully developed by following TDD you won’t have to test the private method separately: Private methods are already being tested by previously written tests.
Read the rest here: http://agiletips.blogspot.com/20 ... s-tdd-and-test.html .
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

主题

0

回帖

4882万

积分

论坛元老

Rank: 8Rank: 8

积分
48824836
热门排行