Choosing the right type of test-double when writing unit tests can be tricky. There are so many of them: Fakes, Stubs, Mocks, Dummies, etc. So I decided to clear things up a bit in this post ๐ ๏ธ.
Some terminology first.
SUT - System Under Test. This is a method, class, or even multiple classes (depending on how you structure your tests) that are currently being unit-tested.
Next, we have the Test-Double. Test-Double is the overarching term for all dependencies you have in your SUT. This term encompasses Fakes, Stubs, Mocks, and Dummies ๐ค.ย
According to Martin Fowler:
- ๐๐๐บ๐บ๐ objects are passed around but never actually used. Usually, they are just used to fill parameter lists.
- ๐๐ฎ๐ธ๐ฒ objects have working implementations, but usually take some shortcut which makes them unsuitable for production (an in-memory database is a good example).
- ๐ฆ๐๐๐ฏ๐ provide canned answers to calls made during the test, usually not responding at all to anything outside what's programmed in for the test.
- ๐ ๐ผ๐ฐ๐ธ๐ are objects pre-programmed with expectations that form a specification of the calls they are expected to receive.
Personally, I always use a mocking during unit testing. Mainly because libraries like Mockito and Mockk are very convenient. They provide all of the tools you might need and are much faster to set up than actual working implementations like Fakes or Stubs.ย
But lately, Iโve been exploring the use of actual implementations like Fakes. This approach should help you uncover problems that Mocks canโt ๐งช.ย
To help you decide what you need for your unit test - I built the decision tree above. Hopefully, youโll find it helpful.ย
You can also get a higher-resolution PDF document here -
What has been your experience with test doubles? Do you prefer one type over the others? Share in the comments below ๐.
Comments