开发者

Is it bad to use control statements in helper libraries that aid testing?

I开发者_高级运维'm finding not being able to use control statements in unit tests very tedious and limiting and am trying to understand where the boundaries are and if I am misunderstanding the guideline. I understand that it's considered bad to have any control logic (looping, if, switch) etc. directly in test code. Is it bad to also have control logic in libraries that factor out common logic in test code (for use exclusively by the test code)? For example, if I have a method that builds an object and that object has a number of component instances (like an order has multiple products) am I not supposed to take a variable that indicates how many components the helper code should create for that object (because taking the variable will apply a loop to build the object graph)? And if that is indeed bad practice for unit tests is it acceptable for another class of testing?


Control flow in tests

I've always found anything beyond the most basic logic in tests to be a bad idea. Tests should be as declarative as possible. If you state what the result is rather than how to achieve the result, it has a few advantages:

Firstly, the test code is usually a lot simpler (Note: "simpler" here doesn't always mean "terser", it just means the intent is simpler to deduce & follow.)

Secondly, it makes it that much harder to ape the system under test's logic. If you ape the system under test, you can have an error in the production code, a corresponding error in the test code and ... a passing test. Two failures and a false sense of security.

Testing Libraries

If you have common test helper types in a library that you rely on, it's ok for those to have logic as long as you test them! Example: Prior to NUnit 2.5's addition of data driven testing, we built our own data-driven testing functionality and used it quite a bit. The data driven testing code itself had tests to ensure that it functioned properly. In my opinion, anything you use to verify correctness itself must be scrutinised even more than usual. You wouldn't want to build on top of something that gives erroneous results, would you? :)

Furthermore, think about NUnit itself. Have a look at its code. Practically everything you use and rely on -- from the runner itself through to the niceties -- is extensively tested for correctness. I feel it is prudent to follow the same practices for your own test libraries.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜