Skip to content

Unit testing with Moa

Evgenii Neumerzhitckii edited this page Jun 21, 2015 · 20 revisions

Here is how to simulate image download in unit tests instead of sending real network requests.

override func tearDown() {
  super.tearDown()

  MoaSimulator.clear()
}

func testDownload() {
  // Create simulator to catch downloads of the given image
  let simulator = MoaSimulator.simulate("35px.jpg")

  // Download the image
  let imageView = UIImageView()
  imageView.moa.url = "http://site.com/35px.jpg"

  // Check the image download has been requested
  XCTAssertEqual(1, simulator.downloaders.count)
  XCTAssertEqual("http://site.com/35px.jpg", simulator.downloaders[0].url)

  // Simulate server response with the given image
  let bundle = NSBundle(forClass: self.dynamicType)
  let image =  UIImage(named: "35px.jpg", inBundle: bundle, compatibleWithTraitCollection: nil)!
  simulator.respondWithImage(image)

  // Check the image has arrived
  XCTAssertEqual(35, imageView.image!.size.width)
}

Fake future requests

One can call MoaSimulator.autorespondWithImage to automatically fake all future requests with matching URLs.

let bundle = NSBundle(forClass: self.dynamicType)
let image =  UIImage(named: "35px.jpg", inBundle: bundle, compatibleWithTraitCollection: nil)!

// Autorespond with the given image to all future request
let simulator = MoaSimulator.autorespondWithImage("35px.jpg", image: image)

// Download the image
let imageView = UIImageView()
imageView.moa.url = "http://site.com/35px.jpg"

// Check the image download has been requested
XCTAssertEqual(1, simulator.downloaders.count)
XCTAssertEqual("http://site.com/35px.jpg", simulator.downloaders[0].url)

// Check the image has arrived
XCTAssertEqual(35, imageView.image!.size.width)

Testing error responses

let simulator = MoaSimulator.simulate("35px.jpg")

// Image download code ... 

simulator.respondWithError()

Or, one can send error responses to all future requests automatically.

MoaSimulator.autorespondWithError("35px.jpg")
Clone this wiki locally