Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ccabanero/4221831a4c527c0453a8506628df34af to your computer and use it in GitHub Desktop.
Save ccabanero/4221831a4c527c0453a8506628df34af to your computer and use it in GitHub Desktop.
Sample iOS Unit Tests: Testing Model Class methods
//
// TEST CODE
import XCTest
@testable import to
class JSONReaderTest: XCTestCase {
let systemUnderTest = JSONReader()
override func setUp() {
super.setUp()
}
func testSUT_CanInstantiateJSONReader() {
XCTAssertNotNil(systemUnderTest)
}
func testSUT_CanFetchJSONFileFromMainBundleAsString() {
let dataAsString = systemUnderTest.fetchJSONAsStringFromMainBundleWithFileName("results")
let numberOfCharacters = dataAsString.characters.count
XCTAssertGreaterThan(numberOfCharacters, 0)
}
func testSUT_CanHandleFileNotFoundWhenFetchingString() {
let nameOfFileNotInBundle = "nofile"
let dataAsString = systemUnderTest.fetchJSONAsStringFromMainBundleWithFileName(nameOfFileNotInBundle)
let numberOfCharacters = dataAsString.characters.count
XCTAssertEqual(numberOfCharacters, 0)
}
}
// PRODUCTION CODE
import Foundation
struct JSONReader {
/**
For fetching a JSON file stored in the main bundle and returning it as a String.
- Parameters:
- fileName: The name of the file to fetch.
- Returns: A string representation of the JSON file.
*/
func fetchJSONAsStringFromMainBundleWithFileName(fileName: String) -> String {
if let filepath = NSBundle.mainBundle().pathForResource(fileName, ofType: "json") {
do {
return try NSString(contentsOfFile: filepath, usedEncoding: nil) as String
}
catch let error as NSError {
print(error.localizedDescription)
return String()
}
}
else {
return String()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment