Test Double in iOS

Tram Ho

Preamble

In an iOS project, if we want to easily write code, from the outset, classes must be broken down independently of each other. And then we will easily write tests for each part. From there, there will be cases where we need to have all the relevant parts to test, or want to test part, but the related parts have not been completed, or the data has not been completed yet. .. then all those problems will be solved based on Test Double

There are many types of Test Double, but to better understand, you can imagine it is also a module but has been stripped down, leaving only the essential components, used to support testing other modules. Depending on the purpose of the test, we will create those simplified mudule.

Dummy

Dummy is that you create an objective but don’t use it, except to combile the code.

For example:

Suppose now we will test the correctness of the area variable:

However, the initialization requires you to have a protocol called SaverProtocol, although in this test case you don’t use that protocol to do anything. So we will create a DummySaver () just to have enough components to run the function test only.

Fake

Fake is an object that has been implemented, but simplified compared to the original. We just leave what we use in that test case, and the rest is omitted. To increase the speed of the test and reduce the complexity of the test.

For example:

Test the correctness of countMessage ()

Instead of making the actual data query call, we will fake the return value in the fetchUsers of fakeUserService. That is how we can make it simple and effective as usual.

Stub

Stubs are objects that are created to replace a specific function that we call and use when testing.

For example:

Now we will test usersCountMessage (), using UsersServiceProtocol. To do this, we will create a StubUsersService:

At first glance, it looks like fake, but the difference of stub is that it is a complete specific function, no internal hard code that data will transfer from outside.

Spy

Spy is a more powerful version of Stub, it will provide information on how the function is called and called many times.

Reuse the example of Dummy:

Now we will test how many times the save () function is called, and the value of saveValue is correct:

Mock

Looking back at the Spy example, there will be times when your test function will have lots of variables to test. Testing becomes difficult and you have to create many SpySaver ()

So Mock will clean up your code in this advanced case.

From the Spy example,

We include assert in the verify () function:

Above is my share about Test Double in iOS, hope to help you. Thank you for reading my article!

Share the news now

Source : Viblo