How to start unit-test old and new code?

痴心易碎 提交于 2019-12-03 01:50:32

Well, the challenge in unit testing is not the testing itself, but in writing testable code. If the code was written not thinking about testing, then you'll probably have a really hard time.

Anyway, if you can refactor, do refactor to make it testable. Don't mix object creation with logic whenever possible (I don't know delphi, but there might be some dependency injection framework to help in this).

This blog has lots of good insight about testing. Check this article for instance (my first suggestion was based on it).

As for a suggestion, try testing the leaf nodes of your code first, those classes that don't depend on others. They should be easier to test, as they don't require mocks.

Writing unit tests for legacy code usually requires a lot of refactoring. Excellent book that covers this is Michael Feather's "Working Effectively with Legacy Code"

One additional suggestion: use a unit test coverage tool to indicate your progress in this work. I'm not sure about what the good coverage tools for Delphi code are though. I guess this would be a different question/topic.

Working Effectively with Legacy Code

One of the more popular approaches is to write the unit-tests as you modify the code. All new codes gets unit tests, and for any code you modify you first write its test, verify it, modify it, re-verify it, and then write/fix any tests that you need due to your modifications.

One of the big advantages of having good unit test coverage is being able to verify that the changes you make don't inadvertently break something else. This approach allows you to do that, while focusing your efforts on your immediate needs.

The alternate approach I've employed is to develop my unit tests via Co-Ops :)

Pierre-Jean Coudert

When you work with legacy code, mock objetcs are really usefull to build unit tests.

Take a look at this question regarding Delphi and mocks: What is your favorite Delphi mocking library?

For .Net unittesting read this : "The Art of Unit Testing: with Examples in .NET"

About best pratices :
What you said is right : Sometimes, it's difficult to write unit tests because of the dependancy between classes... So write unit tests just after or just before ;-) the implementation of the classes. Like this, if you have some difficulties to write the tests, maybe it means you have a design problem !

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!