如何 TDD UIGestureRecognizers? [英] How to TDD UIGestureRecognizers?

查看:35
本文介绍了如何 TDD UIGestureRecognizers?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在尝试编写原本会使用 UIGestureRecognizer 的 TDD 代码时,我发现无法以编程方式验证目标操作.如果没有这个,我不确定我是否可以正确测试它.

While trying to TDD code that would otherwise use a UIGestureRecognizer, I found no way to programatically verify the target-action. Without this, I'm not certain I can properly test it.

如果在 IB 中设置了手势识别器(支持 iOS 5+),则在加载 NIB/故事板时设置目标动作;如果在代码中完成,它使用 initWithTarget:action:,这两者都意味着没有任何模拟能够检测到目标动作.

If the gesture recognizer is setup in IB (with iOS 5+ support) the target-action is setup when the NIB/Storyboard loads; if done in code it uses initWithTarget:action:, both of which mean that no amount of mocking would be able to detect the target-action.

我没有想法了.如果有人成功地测试驱动了 UIGestureRecognizer,我可以使用该建议.

I'm out of ideas. If anyone has successfully test-driven a UIGestureRecognizer I could use the advice.

推荐答案

不幸的是,您正在尝试检查一个框架类,该类在编写时没有考虑到测试,因此没有公开您要验证的状态.这将使断言您要检查的目标-动作对的存在变得困难.在这种情况下,我有三个选项可供您使用,但都不是很好的解决方案:

Unfortunately you're trying to inspect a framework class which wasn't written with testing in mind and so doesn't expose the state you want to verify. That is going to make it difficult to assert on the existence of the target-action pairs you want to check for. In such a case I have three options you might use, none of which are great solutions:

您可以继承 UIGestureRecognizer,覆盖目标操作方法以将注册的对保存在一个集合中,然后您可以向类的用户公开,然后调用这些方法的超类实现.不幸的是,您引入新类只是为了使测试更容易,必须记住使用它们,并且可能必须从 UIGestureRecognizer 转换到您的自定义子类,具体取决于您从何处获得手势识别器引用.

You might be able to subclass UIGestureRecognizer, override the target-action methods to save the registered pairs in a collection you can then expose to users of the class, and then call the superclass implementations of those methods. Unfortunately then you're introducing new classes just to make testing easier, have to remember to use them, and may have to cast from UIGestureRecognizer to your custom subclass depending on where you get a gesture recognizer reference from.

或者,您的测试可以将新版本的目标操作方法混入 UIGestureRecognizer 中,从而为您提供跟踪添加的目标的钩子.只需确保在完成后将原始方法实现交换回原位,否则未来的测试将出现意外行为.

Alternately your test could swizzle new versions of the target-action methods into UIGestureRecognizer giving you a hook to track added targets. Just make sure to swap the original method implementations back into place when you're done or future tests will have unexpected behavior.

最后,您可能会找到一个私有 API 调用,它为您提供了一种在手势识别器上检查已注册目标操作的方法.只需确保私有 API 调用仅保留在您的测试代码中即可.

Finally you might be able to find a private API call which gives you a way to check the registered target-actions on the gesture recognizer. Just make sure that private API call remains only in your test code.

这篇关于如何 TDD UIGestureRecognizers?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆