objective-c - 在 Objective-C 中,让您的委托(delegate)符合多个协议(protocol)是不是不好的做法?

标签 objective-c testing delegates mocking kiwi

这是不好的做法吗?

@property (nonatomic, weak) NSObject<TTModalDelegate, TTTimeEntryVCDelegate> *delegate;

我正在尝试通过模拟这个符合两个协议(protocol)的委托(delegate)来使用 Kiwi 框架测试一些东西。但是,通过阅读文档和互联网搜索,这似乎是不可能的。我可以像这样创建一个符合单一协议(protocol)的模拟委托(delegate):

NSObject *mockDelegate = [KWMock mockForProtocol:@protocol(TTTimeEntryVCDelegate)];

我想知道 Kiwi 是否没有能力让模拟符合多种协议(protocol),因为这是不好的做法。如果是这样,为什么这是不好的做法?

最佳答案

创建符合多种协议(protocol)的类本身并不是坏习惯;这就是语法存在的原因。然而,正如 Apple 在 their documentation 中指出的那样:

If you find yourself adopting a large number of protocols in a class, it may be a sign that you need to refactor an overly-complex class by splitting the necessary behavior across multiple smaller classes, each with clearly-defined responsibilities.

从理论上讲,要求委托(delegate)人遵守多个协议(protocol)也没有任何问题。

但是,您应该考虑通过为每个协议(protocol)创建不同的属性来减少 API 的限制。想想 UITableViewdataSourcedelegate 属性。这不仅会使您的 API 更加灵活,您还可以使用 Kiwi 测试您的类(它的局限性在于无法模拟多个协议(protocol))。

就像 UITableViewUITableViewController 的关系一样,没有什么可以阻止您将两个属性指向同一个对象。

关于objective-c - 在 Objective-C 中,让您的委托(delegate)符合多个协议(protocol)是不是不好的做法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22827096/

相关文章:

ios - UITextFieldViewModeWhileEditing 更改我的 TextField 框架

ios - 无法从iOS 10中的App组共享容器中获取扩展应用程序中的图像

c# - Entity Framework 代码优先 : How to seed a database for unit testing

ios - 一名委托(delegate)两类

c# - 为什么这里的类型是System.Object?

iOS 6 自定义分组 UITableViewCell 大小不正确

objective-c - Objective-C中强弱的区别

Angular 4 : test if window. location.href 已被调用

测试固件

c# - Java 或 C# 中的事件/委托(delegate)