I am continually surprised these days when I ask fellow developers and software writers (including in other languages) and which style of unit testing they prefer and use. Basically their answers are mostly:
What are you talking about? I just write unit tests.
There has emerged a trend in the PHP community to now spec test instead of unit test code. There are two trains of thought from what I understand:
Classical Unit Testing
Classical unit testing is were you unit test a piece of code (e.g. a method) and you will try to not to mock out any of the dependancies of that piece of code. You would rather use the actual objects in your tests which you code uses, and you care about the behaviour delivered by that code. PHPUnit is the PHP industry standard for this practice.
- Single test suite
- Actually tests behaviour
- More confident about tests
- Test suite can run slow over time
- Does not aid in the “design” aspect of the communication.
Mockist / London Schoool of Unit Testing (Spec Testing)
The mockist approach differs from the Classical approach in that you care mainly about how your piece of code communicates with it’s dependancies. You prefer to mock the dependancies as you are using the “test” to aid in the design of your code. Tools such as PHPSpec have been made specifically for this approach however PHPUnit can still be used also.
- Should end up with a better code design.
- Faster to Mock dependancies.
- Runs very fast.
- Test only business logic
- Test results do not give confidence.
- Requires another test suite that actually tests the outcomes (using Behat/RSpec ).
Personally I tend to enjoy the mockist approach as I enjoy the design benefits it brings. Having to think about how an object is communicating with other objects first, tends for me to lead to better code design. I also don’t mind testing the behaviour separately with another tool which checks the system from the outside in. I would say the majority of people out there tend to use the classical approach as could be seen from the recent debate on youtube.
And so the point of this article. Simply I just wanted to highlight the difference to developers so that they think about the “tests” they are writing. What is the purpose? What are you hoping to get out of them?