简体   繁体   English

使用第三方库对Swift进行单元测试

[英]Unit test Swift with third party library

I am using Localytics in my app which is basically just an API that can be used to send analytics data to the server. 我在我的应用程序中使用Localytics,该应用程序基本上只是一个可用于将分析数据发送到服务器的API。
https://docs.localytics.com/dev/ios.html#install-sdk-ios https://docs.localytics.com/dev/ios.html#install-sdk-ios

I work in a project where we have to unit test every single file to make sure that there is atleast 90% code coverage. 我在一个项目中工作,我们必须对每个文件进行单元测试,以确保至少有90%的代码覆盖率。
Since localytics is an external library, I have a wrapper around it to use the API. 由于localytics是一个外部库,因此我周围有一个包装器以使用API​​。

Consider the simple localytics method : 考虑简单的本地化方法:

func tagScreen(screenName: String) {
    Localytics.tagScreen(screenName) 
}

How can I unit test this wrapper? 如何对该包装器进行单元测试?
Is there any suggestions? 有什么建议吗?
How can we write Mocks for the method above? 我们如何为上述方法编写Mocks?

If you want to test the wrapper: as Localytics has static functions to interact with I would go with something like: 如果您想测试包装器:由于Localytics具有静态功能要与之交互,我将采用以下方法:

class LocalyticsWrapper {
  private let tagFunc: (String) -> Void
  init(tagFunc: @escaping (String) -> Void = Localytics.tagScreen) {
    self.tagFunc = tagFunc
  }
  func tagScreen(screenName: String) {
    // maybe some pre-formatting done here or something
    tagFunc(screenName) 
  }
}

Now you can inject mock function and test the wrapper 现在您可以注入模拟功能并测试包装器

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM