TestSpy 0.3.1

TestSpy 0.3.1

Franco Meloni维护。



TestSpy 0.3.1

  • Franco Meloni

TestSpy

Swift 4.0 Build Status Carthage compatible Pod version codecov

Swift 间谍对象框架

要求

  • Swift: 4.0
  • iOS: 9+

创建间谍对象

要创建一个间谍对象,您只需要在测试类中实现 TestSpy 协议。

class TestClass: TestSpy {
     enum Method: Equatable {
         case test
         case testWithArgument(arument: Int)
     }
     
     var callstack = CallstackContainer<Method>()
}

当您要测试的方法被调用时,您必须将方法记录在调用栈中

extension TestClass: TestProtocol {
    func test() {
        callstack.record(.test)
    }
    
    func testWithArgument(argument: Int) {
        callstack.record(.testWithArgument(argument: argument))
    }
}

在测试中使用间谍对象

XCTAssertTrue(spyObject.check(method: .test, predicate: CallstackMatcher.any))

使用 Nimble 在测试中使用间谍对象

expect(spyObject).to(haveReceived(.test))

调用栈匹配器

有一些内置匹配器可以在测试中使用以检查调用栈内容。

主要的匹配器包括

  • times(Int)
  • atLeast(times: Int)
  • never
  • any
  • before(Method)
  • immediatelyBefore(Method)
  • after(Method)
  • immediatelyAfter(Method)

使用说明

XCTAssertTrue(spyObject.check(method: .test, predicate: CallstackMatcher.before(.testWithArgument(argument: 1))))

在 Nimble 中的使用

expect(spyObject).to(haveReceived(.test), .before(.testWithArgument(argument: 1)))

使用 Sourcery 自动生成 Spy 对象

Sourcery 提供了一种很好的自动生成 Spy 对象的方法。您可以在这里找到生成 Spy 对象的示例 Stencil 文件。

要使用它,请执行以下操作

  • 在您的测试项目中添加一个脚本阶段,位于编译源代码阶段之前
sourcery --sources "$SOURCESPATH" --templates "$TEMPLATESPATH" --output "$OUTPUTPATH" --args module="$CURRENTFRAMEWORKNAME",import="Foundation",import="UIKit"...
  • 将此注解添加到您要间谍的协议中 // sourcery: autoSpy
  • 将生成在 $OUTPUTPATH 的文件包含在您的测试项目中

作者

弗朗科·梅洛尼,[email protected]

许可

TestSpy可在MIT许可下使用。有关更多信息,请参阅LICENSE文件。