OCMVerify/Expect in Swift?

与世无争的帅哥 提交于 2019-12-11 13:55:21

问题


I would like to Verify that an expected method is called with the correct parameters in Swift in unit-testing. This was very easily done in Objective-C using the OCMock framework. You could do a combination of partialMocking and running OCMExpect/Verify to assert code paths with the right parameters were being called. Any idea how to do something like this in Swift?


回答1:


Swift doesn't support reflection, so traditional mocking libraries aren't feasible. Instead, you need to create your own mock. There are at least two approaches to do this.

  1. Create a testing subclass of the class under test. This is partial mocking. Avoid this if possible.
  2. Use an interface instead of a class. Create a testing implementation of the interface.

Hand-crafted mocks aren't hard. You want to

  • Count the number of calls to a method
  • Capture its arguments
  • Simulate its return value

It is a lot of boilerplate. There are libraries out there that can auto-generate this code.



来源:https://stackoverflow.com/questions/35520332/ocmverify-expect-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!