Unit test - result0924/iosLearning GitHub Wiki

A PATTERN FOR WRITING GOOD TESTS

  • Arrange: 初始化的過程(Giver a client and a sut)
  • Act: 執行測試的目標,並取得實際結果(When we invoke sut.load())
  • Assert: 驗證結果(Then assert that a URL request was initiated in the client)

How to mock singleton

  1. Make the shared instance a variable
static let shared = HTTPClient() -> static var shared = HTTPClient()
  1. Move the test logic from RemoteFeedLoader to HTTPClient
HTTPClient.shared.requestedURL = URL(string: "https://a-url.com") -> 
HTTPClient.shared.get(from: URL(string: "https://a-url.com"))
  1. Move the test logic to a new subclass of HTTPClient.(the spy that it is targeting, the test specifically)
class HTTPClientSpy: HTTPClient {
    ....
}
  1. Swap the HTTPClient shared instance with the spy subclass during tests.
  2. Remove HTTPClient private initializer since it's not a Singleton anymore.

Note

  • Spy is just an implementation of the protocol rather than a subtype of the abstract class

Refer