Build Unit Tests or Functional Tests?

1972 Honda CB350

1972 Honda CB350

The headline is a trick – you do both.

It’s 2016, if you’re still out there writing code with no unit tests or functional tests, you’re not doing your job correctly.

Every time I write a method, I write a unit test. The unit test checks that the method does what I think it should be doing.

public function add($num1, $num2)
{
   if (!is_numeric($num1) || !is_numeric($num2) {
       throw new MathNotNumericException();
   }
   return $num1 + $num2;
}

For this method I would write two tests. One would test that the math works. If I call $this->add(1, 1) I should get 2. Another test will check that my numeric validation works as expected – I should get a MathNotNumericException if I call something like this $this->add(‘Stop’, ‘That’).

I also create functional tests for slices of the application’s functionality. For instance, if I had built a new user registration system, I would create a test that sets up a bunch of dummy data and calls the necessary methods to register a new user. The functional test could access dozens of methods and processes.

Unit tests give the developer confidence that an individual chunk of code works. Functional tests make sure that when all of the methods are used together, that they’re doing what is expected as part of the entire application.

To use a motorcycle example, checking tire pressure would be akin to a unit test. Hopping on the bike and seeing how the entire bike rides, or functions, would be a functional test. You need them both. I can’t count the number of bugs my tests have caught before rolling out code to production.


Buy my Symfony Getting Started eBook on Amazon.

Buy my new book Symfony Getting Started

Buy my new book Symfony Getting Started

Share Button

Leave a Reply

Your email address will not be published.