Created
November 22, 2022 12:11
-
-
Save glennposadas/b81cdfd8826d7820a7ffc08a6e8bfa70 to your computer and use it in GitHub Desktop.
Answer to iOS Question.
This file contains 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
Given we must unit test the function in ClassToTest, how would you change the code below to allow us to achieve this? | |
Notes: | |
These will be unit tests so must work offline (ie does not rely on the API) | |
No need to write the tests, we just how we could change the code to make it testable. | |
We can't use any third party mocking libraries | |
Feel free to write your answer as text or pseudocode | |
class API { | |
func fetchItems(completion: (Result<[Item], Error>) -> Void) { | |
// Gets items from some hosted API | |
} | |
} | |
class ClassToTest { | |
private(set) var stateList = [String]() | |
func functionToTest() { | |
stateList.append("Loading") | |
API().fetchItems { result in | |
switch result { | |
case .success(_): | |
stateList.append("Success") | |
case .failure(_): | |
stateList.append("Failed") | |
} | |
} | |
} | |
} | |
------- | |
Answer: | |
Indeed, in unit test, we are merely testing our own codes without the dependencies, in as small unit as possible. | |
Therefore, we would want to mock our `API`. It's not always that I'm required to create my own highly testable | |
Networking class for a project, but let me do my best to explain one idea to do this. | |
I think first off, we could add a init function in our `API` class. This will take a `URLSession` object that | |
can make our class a little more flexibe. In Foundation framework, we have an interface called `(NS)URLProtocol` and | |
a class called `(NS)URLSessionConfiguration`. | |
We could make utilize these to create our mocked session and request. We could also add more twist like adding | |
delay to our stubbing. | |
From there we can now proceed to coding our test cases. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment