When it comes to unit testing, testing a component is a crucial way to validate our component is working properly or not. By definition, a component is an implementation detail, it can be a class, or struct, or similar to that.
Let’s say we have a use case component. This use case is responsible to talk to the database to request some items and returns it. Since it it will talk to a database, then the request is async.
If we want to test this use case component, let’s call it
LoadTransactionsFromLocalUseCase , we can test it using the
real component that talks to a
real database . This test is works, but this is not a unit testing, but rather, an integration testing.
Integration testing is a testing between components, or to a real framework implementation. If we test using this integration testing, it is going to work. But, we are limiting the options, since we can’t tell the database to fail, or fail with custom error, or success with some predefined values. moreover, integration testing can left a side effects, such as saved data, or deleting some real data.
We can avoid this by using the test double in unit testing. This is a concept, to test a component that we want to test, the System Under Test (SUT), we can use another component as a helper with predefined strategy or behavior. This concept is explained below :
In this diagram, the SUT component, will talks to a test double component, which is not a real component. Usually, we as developer, defined that component inside the test module, because it is not related to the production code.
There are few test doubles, and two of them are Stub and Spy. Both test doubles used in different cases. Let’s take an example of stub.
Stub is one of the test double, that has a predefined result. In this case, this test double component can helps triggering desired behavior of a SUT. Let’s say we are expecting the SUT to return a specific error, then, we inject the component configured using stub technique that returns an error, so that the SUT return in a fail condition.
Another benefit of using test double is it fits well on the unit testing strategy. If we are using more unit tests than any other tests, it means that we are following good testing strategy layer, which will make our test run fast, since there are more unit tests strategy than other tests strategy.
When it comes to test double, it is wise enough to keep the test double component as close as possible to the tests class, since that test double is only used by the test class. Expose the class one level higher, if only we shared the same test double on different test case class.
Next article, we will learn how to implement a stub as a test double when doing unit testing.
- Martin Fowler, TestDouble : https://martinfowler.com/bliki/TestDouble.html
- iOS Unit Testing by Example, Jon Reid : https://pragprog.com/titles/jrlegios/ios-unit-testing-by-example/
One thought on “Introduction to Test Double : What and Why We Need It?”