Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting Started with Unit Testing

Tags:

Unit testing is, roughly speaking, testing bits of your code in isolation with test code. The immediate advantages that come to mind are:

  • Running the tests becomes automate-able and repeatable
  • You can test at a much more granular level than point-and-click testing via a GUI

Rytmis

My question is, what are the current "best practices" in terms of tools as well as when and where to use unit testing as part of your daily coding?

Lets try to be somewhat language agnostic and cover all the bases.

like image 279
Rob Allen Avatar asked Aug 19 '08 20:08

Rob Allen


People also ask

Is unit testing easy to learn?

But, being a white box software testing technique, unit testing is an in-depth process that requires a lot of knowledge about the code and how it interacts with other parts of the project. As a result, it can be hard to start writing unit tests, especially if you are new to the codebase.

How long does it take to learn unit testing?

They told me to learn unit testing and write unit tests for a project that has 3000 lines and 35 classes approximately in 3 weeks. I did read Art of Unit Testing in 2 days and getting used to unit tests took another day already.

Is unit testing hard?

Developers experience Unit Testing as difficult when they run into these kinds of problems: Classes are tightly coupled to other classes, which makes it hard to test because you need to control those other classes as well when you are writing your tests. This is very, very difficult and very error prone.


2 Answers

Ok here's some best practices from some one who doesn't unit test as much as he should...cough.

  1. Make sure your tests test one thing and one thing only.
  2. Write unit tests as you go. Preferably before you write the code you are testing against.
  3. Do not unit test the GUI.
  4. Separate your concerns.
  5. Minimise the dependencies of your tests.
  6. Mock behviour with mocks.
like image 88
Johnno Nolan Avatar answered Sep 18 '22 22:09

Johnno Nolan


You might want to look at TDD on Three Index Cards and Three Index Cards to Easily Remember the Essence of Test-Driven Development:

Card #1. Uncle Bob’s Three Laws

  • Write no production code except to pass a failing test.
  • Write only enough of a test to demonstrate a failure.
  • Write only enough production code to pass the test.

Card #2: FIRST Principles

  • Fast: Mind-numbingly fast, as in hundreds or thousands per second.
  • Isolated: The test isolates a fault clearly.
  • Repeatable: I can run it repeatedly and it will pass or fail the same way each time.
  • Self-verifying: The Test is unambiguously pass-fail.
  • Timely: Produced in lockstep with tiny code changes.

Card #3: Core of TDD

  • Red: test fails
  • Green: test passes
  • Refactor: clean code and tests
like image 43
Jon Limjap Avatar answered Sep 19 '22 22:09

Jon Limjap