Monday, 3 December 2018

UI/Unit Test Async Code

Check example code at Github:
https://github.com/Sylvia-YiyinShen/TestAsyncCode

This tutorial covers:
  • Unit testing async code via build-in XCTestCase
  • Unit testing async code via Quick/Nimble
  • UI testing async code

ExampleViewModel prepared for this tutorial as below,  just mocking an API call and exposing list data.




Unit testing

Now let's look at a test which will not be able to pass:



Since fetchBookList is an async function, the last two assertions will fail.  Although we can test bookList inside the completion block of fetchBookList, it doesn't work for other public properties of viewModel.

We need the help of XCTestExpectation. A succeeding example is as below:



If you are familiar with Quick/Nimble, we need the keyword toEventually instead of XCTestExpectation




UITesting

A failing test example just checking the existence of a label which will only appear on completion of the async function.


A succeeding test via sleep() which is not the good practice. Since we would never know the minimum time to complete the async function and we always have to make it longer. If sleep() has been heavily used through thousands of tests, there will be considerable time wasted.


Solution: 




No comments:

Post a Comment