0

I am using Xcode version - Version 9.4.1 (9F2000).

I am trying to create custom logs for tests running with XCUITest by overwriting XCTestObservation class and registering it with test class.

Observer class: TestObserver

class TestObserver : NSObject, XCTestObservation {

    public func testSuiteWillStart(_ testSuite: XCTestSuite) {
      print("I am inside function testSuiteWillStart --> \(testSuite)")
} }

Setup in my test case:

class MyTestCase: XCTestCase{

override class func setUp() {
    super.setUp()
    XCTestObservationCenter.shared.addTestObserver(TestObserver())
}}

I tried running test using Xcode and Fastlane both but the function testSuiteWillStart is not getting called at all. Has anyone faced similar issue?

pkamb
  • 33,281
  • 23
  • 160
  • 191
Jinesh
  • 60
  • 6

2 Answers2

2

The function testSuiteWillStart will be called only when the Test Observer is added,

You can add observer using following line of code:

XCTestObservationCenter.shared.addTestObserver(observer) //observer is instance of object that confirms to XCTestObservation

Steps to follow:

  1. Create a class that confirms to XCTestObservation protocol
  2. Add class name in test bundle info.plist for key NSPrincipalClass

Step 1:

class SOTestObserver: NSObject, XCTestObservation {


    override init() {
        super.init()
        XCTestObservationCenter.shared.addTestObserver(self)
    }

    func testBundleWillStart(_ testBundle: Bundle) {
        print("---## \(#function), URL: \(testBundle.bundleURL)")
    }
}

Step 2:

if your project name has space for example My App then add following in info.plist

<key>NSPrincipalClass</key>
<string>My_AppUITests.SOTestObserver</string> 

if your project name does not have spaces then add following

<key>NSPrincipalClass</key>
<string>$(PRODUCT_NAME).SOTestObserver</string> 
Saif
  • 2,678
  • 2
  • 22
  • 38
0

You need to call your Observer calls in UITest info.plist. Info.plist, create a new key "Principal Class" and Give a value as TestTarget. E.g. UITests.TestObserver

While your testobserver class should look like

class TestObserver: NSObject, XCTestObservation {
    override init() {
        super.init()
        XCTestObservationCenter.shared().addTestObserver(self)
    }
   func testBundleWillStart(_ testBundle: Bundle) {
    print ("start")
   }
}
iamMobile
  • 959
  • 2
  • 17
  • 35