Skip to content

Unit testing with Moa

Evgenii Neumerzhitckii edited this page Jan 14, 2017 · 20 revisions

Here is how to simulate image download in unit tests with Moa.

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 = Bundle(for: self.classForCoder)
  let image =  UIImage(named: "35px.jpg", in: bundle, compatibleWith: nil)!
  simulator.respondWithImage(image)

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

Respond automatically

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

let bundle = Bundle(for: self.classForCoder)
let image =  UIImage(named: "35px.jpg", in: bundle, compatibleWith: 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()

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

MoaSimulator.autorespondWithError("35px.jpg")

Removing moa simulator

Call MoaSimulator.clear() after the unit test to stop using the simulator and use the real moa downloader in subsequent tests.

override func tearDown() {
  super.tearDown()

  MoaSimulator.clear()
}