开发者

How to start with unit testing?

First,I don't 开发者_如何学Gowant to do TDD. I'd like to write some code and then just write the unit tests for the important stuff.

I know the tools. I know how to write a unit test.

I wrote some code (couple off classes) and I don't know where to start. I'm missing the semantic.

How to pick up what to unit test ?

Should I unit test every class extra ?

Should I try to simulate every possible variation of method's parameters ?


The idea with unit testing is to test pieces of code. We use TDD at my company which works create. We write tests for every possible option of a function. So to answer your three questions;

  1. How to pick up what to unit test ?

    It's useless to write unit tests for code or functions that contain no intelligence. This actually is what needs to happen when you strictly follow TDD. But if it's obvious what the function returns and you're sure nothing can go wrong, then you probably don't have to write an test for it. Though it's better to do so.

  2. Should I unit test every class extra?

    What exactly do you mean by this? If the question is do you need to test classes the answer is no. Unit testing is for testing the smallest piece of code. Mostly functions and constructors. What you want to know is if your function gives the result you want and you want it to return the desired result or throw an nicely handeled exception no matter what parameter-value you send to the function

  3. Should I try to simulate every possible variation of method's parameters ?

    You should. That's the whole idea of writing a unit test. You want to test a piece of code an rule out every single thing that can go wrong. Parameters are the most important here. What happens if a string-parameter contains html for example? And what if an required parameter is NULL? Or an empty string. Every option should be tested to rule out the possible things that can go wrong.

If you're using the .net framework it is very interessting to look at the Moq framework. Shortly put it is an framework allowing you to create an fake object of some type and you can validate your test against it to check if the result is as expected using several different parameter and return values. You can read about it in Scott Hanselmans blog post.


Should I try to simulate every possible variation of method's parameters ?

You should have a look at Pex which can generate input values for your parameterised tests that provide the greatest code coverage.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜