Unit tests dos and don'ts

farhanrosenborg

farhan

Posted on December 5, 2020

Unit tests dos and don'ts

When writing a unit tests. There are couple of things to do and couple of things which should be avoided. In this article I have listed the dos and don'ts with regards to unit testing.

dos

  1. Test only the public functions.
  2. Test each and every public function. In a ideal world a class should have only one public function and its dependencies.
  3. Mock every dependency.
  4. Test should cover success and failure, both aspects of a code.
  5. Test that every raised exception is tested.
  6. Always specify how many times a function is expected to be called while testing a piece of code.
  7. Test setup pain is a smell, which means your code needs to be refactored.
  8. Code coverage should be 100%, which means each and every line of the tested class was reached.
  9. Live deployment should not work with failing unit tests.
  10. Add tests to classes which are missing unit tests.
  11. Write meaningful names which explain what the test is doing example names testUserRegistrationWasSuccessful, testUserRegistrationWasNotSuccessful, testUserRegistrationRepositoryThrowsException

don'ts

  1. Tested class should never talk to database, file, network resources etc.
  2. Dependencies in tested class should not create real class objects.

http://www.rosenborgsolutions.com/articles/phpunit/phpunit-best-practice

đź’– đź’Ş đź™… đźš©
farhanrosenborg
farhan

Posted on December 5, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related