unit testing custom UIView
I have a graphic application using CoreGraphics framework,
while i have unit test suits for the model files i can't seem to understand how to create a unit test for my custom UIView,
my goal is setting basic properties of view and see the draw functions result, although in my setters i called: [self setNeedsDisplay]; my 'drawRect' function is not being called from the unit test although it is being called from the real application
is there a way to draw in unit test project? what is the best practice/ tools to test ui projects?
thanks
In general unit testing views isn't the right thing to do. Unit testing is meant to validate discrete atoms of logic, and if you're factoring your code properly 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 app is actually running (either in the simulator or on device). UIAutomation has functions (the various view methods, and captureRectWithName()
) that allow you to find and screenshot specific views. You can then hook it up to, for example, ImageMagick's command line compare tool to validate that you're drawing the correct thing.
A simple way to test drawing is to first make the drawing look the way you want (so no TDD). Then make a test which renders the drawing into a PNG. Use a #if conditional to switch the test code between capturing a baseline PNG, and comparing against that PNG.
Rendering can change slightly in new OS versions. So stick with a single OS for baseline image testing. Grab a new baseline when you need to.
With this kind of testing in place, you can then refactor your drawing code. If it renders the same image, your latest changes are good. If there's a difference, you have to make an eyeball decision about whether or not to accept the change. (And if you do, capture a new baseline.)
Edit: These days, instead of doing all that by hand, I'd use iOSSnapshotTestCase. When there is a test failure, instead of just giving a "something went wrong" result, it saves the image. This way, you can do a side-by-side comparison without having to manually launch your app and navigate to the view in question. It also simulates rendering to different devices in different orientations, which is really great for checking autolayout.
I personally think that you should test any rendering you do with your view using XCUI tests. However any business logic that creates the said custom rendering, or any maths, or logic you have added should be tested and done isolated from any other class.
Therefore your UIAutomation tests will check if your view is being rendered, but your unit tests will validate any maths or business logic that might exist in it.
链接地址: http://www.djcxy.com/p/70200.html上一篇: javascript websocket onmessage event.data
下一篇: 单元测试自定义UIView