Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to unit test UITableView?

I am trying to unit test UITableView but I have no idea how to do it. I have a view controller that has a table view in it. Each prototype cell has a custom table view cell class with outlets attached to it.

Now, I want to test both of these components separately. Firstly, I want to test if the data inside the table view cell is correct by creating the prototype cell separately. Secondly, I want to populate my table view with random data and test whether the objects are correct etc. How can I do both of these?

For testing the cell itself, I have no idea how to create the cell separately and check it by sending data to it. So, my custom class has small functions to set data to cell instead of directly assigning data to label, button, image. I want to test those functions. But I can't check it if I am not rendering it.

For testing the components, my problem is different in the sense that, I want to change the data that is coming to it. So, instead of reading the data from API, I want to read it normally but I don't know how to change viewDidLoad to work with local objects instead of network objects.

like image 661
Gasim Avatar asked Dec 19 '22 08:12

Gasim


1 Answers

The short answer is: you don't. As a general rule of thumb, in unit testing you should be testing the business logic, not the UI. Views, in general, should be so void of functionality that there is no reason to run unit tests against them.

Edit: to expound on this a bit more. I prefer to only store information in a view that's related to how it looks, where's it's positioned, etc. This can usually be programmed declaratively In addition, the view will have the smallest functionality necessary to convert user interaction from your UI framework into an interface for your presenter (if using MVP) or controller (if using MVC). The presenter or controller could then be tested to your heart's content through the same interface.

I also find you can avoid a lot of complexity and bugs if you develop a preference for creating new views rather than rerendering existing views. This isn't always feasible. But when it is, the view has do a lot less dynamic work and instead just show the model that would have been passed into its constructor.

like image 155
Nathan Avatar answered Jan 05 '23 17:01

Nathan