Individual testing of UIView

I have a graphics application using the CoreGraphics framework,

as long as I have a unit test suitable for model files, I cannot figure out how to create a unit test for my custom UIView,

My goal is to set the basic properties of the view and see the result of the draw function, although in my setters I called: [self setNeedsDisplay]; my drawRect function is not being called from unit test, although it is being called from a real application

Is there a way to draw in a unit test project? what is the best practice / tools for testing ui projects?

thanks

+7
source share
3 answers

An easy way to check a drawing is to first make the drawing exactly as you want (therefore TDD). Then do a test that turns the drawing into PNG. Use the #if clause to switch test code between capturing a base PNG and comparing it to that PNG.

Rendering may change slightly in newer versions of the OS. Therefore, stick to one OS to test the original image. Take a new baseline when you need to.

With this kind of testing, you can reorganize your drawing code. If it displays the same image, your recent changes are good. If there is a difference, you must decide whether to accept or not to accept the changes. (And if you do, take a new baseline.)

Edit: Nowadays, instead of doing all this manually, I would use FBSnapshotTestCase . When a test fails, instead of just giving the result β€œsomething went wrong,” it saves the image. Thus, you can make side-by-side comparisons without having to manually launch the application and move on to the view in question. It also simulates rendering for different devices in different orientations, which is really great for checking auto power off.

+2
source

In general, unit tests are not suitable. Unit testing is designed to test discrete atoms of logic, and if you use your code correctly, there should be very little logic in your views.

A more successful approach might be to use the UIAutomation framework (or your automation tool of choice). This allows you to automate simulated user interaction while the application is running (either in the simulator or on the device). UIAutomation has functions (various viewing methods and captureRectWithName() ) that allow you to find and display specific views. You can then connect it, for example, to the ImageMagick Command Line Comparison Tool to confirm that you are drawing the right thing.

+2
source

I personally believe that you should test any rendering you do with your view using XCUI tests. However, any business logic that creates the specified user-defined rendering, or any mathematical data or logic that you add, must be verified and isolated from any other class.

Therefore, your UIAutomation tests will check if your view is displayed, but your unit tests will check any math or business logic that may exist in it.

0
source

All Articles