Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Testing in Swift - SwiftSummit 2015

Jan Riehn
March 30, 2015

Testing in Swift - SwiftSummit 2015

Jan Riehn

March 30, 2015
Tweet

More Decks by Jan Riehn

Other Decks in Programming

Transcript

  1. import XCTest class SummitTest: XCTestCase { override func setUp() {

    super.setUp() } override func tearDown() { super.tearDown() } func testExample() { XCTAssert(true, "Pass") } func testPerformanceExample() { self.measureBlock() { } } }
  2. func testShouldReceiveDataFromSwiftSummit() { //given let url = NSURL(string: "http:/swiftsummit.com")! var

    expectation = expectationWithDescription(“should receive data”) var dataReceived: NSData? = nil //when let task = NSURLSession.sharedSession().dataTaskWithURL(url) {(data, response, error) in dataReceived = data expectation.fulfill() } task.resume() waitForExpectationsWithTimeout(5, handler: nil) //then XCTAssertNotNil(dataReceived, "should receive data”) }
  3. /// A protocol that produces a reflection interface for a

    value. protocol Reflectable { /// Get the mirror that reflects this object. func getMirror() -> Mirror } protocol MirrorType { /// Copy the value out as an Any. var value: Any { get } /// Get the type of the value. var valueType: Any.Type { get } /// Get the number of logical children this value has. var count: Int { get } ... }
  4. @objc protocol Connection { func fetchData() -> String } class

    ServerConnection : NSObject, Connection { func fetchData() -> String { return "real data returned from other system" } }
  5. - (void)testMockingAnObject { id mock = OCMClassMock([ServerConnection class]); OCMStub([mock fetchData]).andReturn(@"stubbed!");

    Controller *controller = [Controller newController]; controller.connection = mock; [controller redisplay]; OCMVerify([mock fetchData]); XCTAssertEqualObjects(@"stubbed!", controller.data, @"Excpected stubbed data."); }
  6. func testShouldReceiveDataFromSwiftSummit() { //given let url = NSURL(string: "http:/swiftsummit.com")! var

    dataReceived: NSData? = nil //when let task = NSURLSession.sharedSession().dataTaskWithURL(url) {(data, response, error) in //then XCTAssertTrue(false) } task.resume() }
  7. assertThat(x, equalTo(2)) // assertThat(x, equalTo(3)) // GOT: 2, EXPECTED: equal

    to 3 assertThat("foobarbaz", containsString("bar")) // assertThat("foobarbaz", containsString("bla")) // GOT: "foobarbaz", EXPECTED: contains "bla" let array = ["foo", "bar"] assertThat(array, hasCount(2)) // assertThat(array, contains("foo", "bar")) // assertThat(array, contains(equalTo("foo"), equalTo("bar"))) // assertThat(array, contains(equalTo("foo"))) // GOT: [foo, bar] (unmatched item "bar"), // EXPECTED: a sequence containing equal to foo var optional: Int = 1 + 1 assertThat(optional, present()) // assertThat(optional, nilValue()) // GOT: Optional(2), EXPECTED: nil