Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to properly use Unit Tests (in any language)

I've never really written unit tests before (or tests, for that matter, really). I tend to obsessively run/compile after writing even the smallest bit of code to check for errors. I've been doing a bit of reading up on unit tests lately, and I'm curious how to best go about using/implementing them. My main language as of late has been Python, but I think this is a pretty language agnostic question. Does anyone have some tips (or good reading) on how to do this properly?

Thanks!

like image 967
tjsimmons Avatar asked Nov 01 '10 18:11

tjsimmons


People also ask

Should you write unit tests for everything?

The answer to the more general question is yes, you should unit test everything you can. Doing so creates a legacy for later so changes down the road can be done with peace of mind. It ensures that your code works as expected. It also documents the intended usage of the interfaces.

How do you structure unit tests?

A typical unit test contains 3 phases: First, it initializes a small piece of an application it wants to test (also known as the system under test, or SUT), then it applies some stimulus to the system under test (usually by calling a method on it), and finally, it observes the resulting behavior.

Should you write unit tests before code?

It often makes sense to write the test first and then write as much code as needed to allow the test to pass. Doing this moves towards a practice known as Test-Driven Development (TDD). Bluefruit uses a lot of TDD because it helps us to build the right product without waste and redundancies.


2 Answers

I would suggest Chapter 13 of Dive Into Python.

like image 160
bhadra Avatar answered Sep 28 '22 01:09

bhadra


Unit testing is one thing, another thing to consider is test driven development, where the act of writing the tests first affects the design/ feel of the finally delivered code - hopefully for the better. I find this helps especially if the problem domain is not fully understood at the start of programming.

Clarke Ching does a good one hour talk about TDD using excel. If you spend an hour reading through this, you should get the idea.

http://www.clarkeching.com/files/tdd_for_managers_and_nonprogrammers_using_excell_and_vba_final.pdf

You know you have arrived with unit testing when xUnit Test Patterns is an enjoyable read. http://www.amazon.co.uk/xUnit-Test-Patterns-Refactoring-Signature/dp/0131495054/ref=sr_1_1?ie=UTF8&qid=1288638075&sr=8-1

That is probably a big ask initially though, and I would suggest something thinner about either refactoring or TDD would be a more gentle introduction to this fascinating subject.

like image 31
David Turner Avatar answered Sep 28 '22 01:09

David Turner