farhan
Posted on December 5, 2020
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
- Test only the public functions.
- Test each and every public function. In a ideal world a class should have only one public function and its dependencies.
- Mock every dependency.
- Test should cover success and failure, both aspects of a code.
- Test that every raised exception is tested.
- Always specify how many times a function is expected to be called while testing a piece of code.
- Test setup pain is a smell, which means your code needs to be refactored.
- Code coverage should be 100%, which means each and every line of the tested class was reached.
- Live deployment should not work with failing unit tests.
- Add tests to classes which are missing unit tests.
- Write meaningful names which explain what the test is doing example names testUserRegistrationWasSuccessful, testUserRegistrationWasNotSuccessful, testUserRegistrationRepositoryThrowsException
don'ts
- Tested class should never talk to database, file, network resources etc.
- Dependencies in tested class should not create real class objects.
http://www.rosenborgsolutions.com/articles/phpunit/phpunit-best-practice
đź’– đź’Ş đź™… đźš©
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.