Swiftpack.co -  f-meloni/TestSpy as Swift Package
Swiftpack.co is a collection of thousands of indexed Swift packages. Search packages.
Swift Framework for Spy Objects
.package(url: "https://github.com/f-meloni/TestSpy.git", from: "0.5.0")


Swift 5.0 Build Status Carthage compatible Pod version codecov

Swift Framework for Spy Objects


  • Swift: 4.0+
  • iOS: 9+

Create a spy object

To create a spy object you just have to implement the TestSpy protocol on your test class.

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

Then when the method you want to test is called you have to record the method in the callstack

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

Use the spy object in tests

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

Use the spy object in tests with Nimble


Callstack Matchers

There are some default matchers that can be used on the test to check that callstack content.

The main matchers are:

  • 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))))

Usage with Nimble

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

Automatically generate Spy Objects with Sourcery

Sourcery offers a good way to automatically generate spy objects. You can find an example stancil file to generate Spy Objects here

to use it:

  • add a script phase, before the compile sources phase, in your test project with:
sourcery --sources "$SOURCESPATH" --templates "$TEMPLATESPATH" --output "$OUTPUTPATH" --args module="$CURRENTFRAMEWORKNAME",import="Foundation",import="UIKit"...
  • add this annotation to the protocol you want to spy // sourcery: autoSpy
  • include the files generated at $OUTPUTPATH on your test project


Franco Meloni, franco.meloni91@gmail.com


TestSpy is available under the MIT license. See the LICENSE file for more info.


Stars: 11
Last commit: 2 weeks ago

Ad: Job Offers

iOS Software Engineer @ Perry Street Software
Perry Street Software is Jack’d and SCRUFF. We are two of the world’s largest gay, bi, trans and queer social dating apps on iOS and Android. Our brands reach more than 20 million members worldwide so members can connect, meet and express themselves on a platform that prioritizes privacy and security. We invest heavily into SwiftUI and using Swift Packages to modularize the codebase.

Release Notes

2 years ago

Swiftpack is being maintained by Petr Pavlik | @ptrpavlik | @swiftpackco | API