Home > Mobile >  How to handle crashes in unit test target in Mac OS application
How to handle crashes in unit test target in Mac OS application

Time:09-18

In application we can register the below set of code to catch the crashes

        signal(SIGILL) { _ in
        print("Signal Kill")
    }
ncaughtExceptionHandler { exception in
        print("Exception caught: \(exception)")
    }

But I want to achieve this in Unit test target as well. How can I do this?

CodePudding user response:

If you need to have the signal handlers to be installed before the unit tests run, you can create a .m file similar to this:

// setup.m

static void __attribute__((constructor)) setup() {
    // switch to Swift as soon as possible :)
    [MySignalHandlers installAllHandlers];
}

, and then create a Swift class that does the actual work. Ofcourse you could write the signal handlers in Objective-C, but since you already have them in Swift, you can reuse that logic.

// MySignalHandlers.swift

class MySignalHandlers: NSObject {
    @objc static func installAllHandlers() {
        // do your thing here
    }
}

Functions decorated with __attribute__((constructor)) are automatically executed when the binary that holds them is loaded, so this guarantees that the signal handlers are installed before any unit tests run.

  • Related