3

In XCTest with swift you can define mock objects in the test function you need it in. Like so

func testFunction(){
    class mockClass: AnyObject{
        func aFunction(){
        }
    }
}

I'm trying to use these mock objects to test that another function sends out the correct notification given a certain condition (in my case that the success notification is broadcast with a 204 status code to an object.

The problem I am having is that i get an "Unrecognised selector" runtime error even though the deletedSuccess() function is clearly there/

Heres some code dump

func testDelete(){
    let expectation = expectationWithDescription("Post was deleted")

    class MockReciever : AnyObject {
        func deleteSuccess(){
            println("delete successfull")
            expectation.fulfill()
        }
    }

    let mockReciever = MockReciever()
    NSNotificationCenter.defaultCenter().addObserver(mockReciever, selector: "deleteSuccess", name: PostDeletedNotification, object: post)
    let response = NSHTTPURLResponse(URL: NSURL(), statusCode: 204, HTTPVersion: nil, headerFields: nil)
    let request = NSURLRequest()
    post.deleteCompletion(request, response: response, data: nil, error: nil)

    waitForExpectationsWithTimeout(30, handler: { (error) -> Void in
        if error != nil{
            XCTFail("Did not recieve success notification")
        } else {
            XCTAssertTrue(true, "post deleted successfully")
        }
        NSNotificationCenter.defaultCenter().removeObserver(mockReciever)
    })
}

Is there some sort of problem with using mock objects and selectors like this that I don't know about?

AndyRyan
  • 1,500
  • 12
  • 23

1 Answers1

6

You don't have to implement mock objects to test notifications. There is a -[XCTestCase expectationForNotification:object:handler:] method.

And here's an answer on how to receive notifications from NSNotificationCenter in Swift classes that do not inherit from NSObject. Technically it's a duplicate question.

Community
  • 1
  • 1
kean
  • 1,561
  • 14
  • 22
  • Not exactly a duplicate question. I tried making mock objects of NSObject, and UIViewController (since it's a view controller that receives the notification in the app itself) and I got the same error every time. My question is whether mock objects can be used as the observer. I will try the expectationForNotification function tomorrow though and let you know if it works – AndyRyan Aug 13 '15 at 19:58
  • Worked a treat thanks. Even using the completion block for testing things that should happen before the notification is sent – AndyRyan Aug 14 '15 at 09:01
  • Yeah, it's a great way to test NSNotificationCenter. There is a similar method to test KVO too. – kean Aug 14 '15 at 09:01