Last active
June 10, 2019 22:06
-
-
Save ccabanero/4221831a4c527c0453a8506628df34af to your computer and use it in GitHub Desktop.
Sample iOS Unit Tests: Testing Model Class methods
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// 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