vinhnx / notes

my today I learn (TIL) journal, includes everything that I found interesting, not necessarily relates to programming
44 stars 2 forks source link

Codable, URLSession, Networking unit testing using stub/mock data #135

Open vinhnx opened 6 years ago

vinhnx commented 6 years ago

tl,dr: Check my sample repository on how to build a DIY network client and serializing into model using Codable, with just a few lines of code. Also a unit testing that network client with stub example.

https://github.com/vinhnx/UnitTestingNetworkWithStub_Demo

Reference:

vinhnx commented 6 years ago

We can use Decoder's keyDecodingStrategy for more fine grain control over decoding strategy.

For example, we want the compiler to automatically convert snake case from json response into our camel case model definition:

let data = { "some_value": 123 }.data(using: .utf8)

struct Foo: Decodable {
  var someValue
}

do {
  let decoder = JSONDecoder()
  decoder.keyDecodingStrategy = .convertFromSnakeCase

  // foo.someValue will be automatically converted from json snake case
  let foo = try decoder.decode(Foo.self, from: data)

} catch (let decodingError) {
  print(decodingError)
}

NOTE that using key coding strategy has "nominal performance cost"

  • Note: Using a key decoding strategy has a nominal performance cost, as each string key has to be inspected for the _ character. --- from KeyDecodingStrategy.convertFromSnakeCase header
vinhnx commented 6 years ago

Testing NetworkRequest and User model by faking/stubbing the process

https://github.com/vinhnx/UnitTestingNetworkWithStub_Demo/blob/master/UnitTestingNetworkWithStub_2Tests/NetworkRequestTests.swift

Reference: http://hoangtran.me/ios/testing/2016/09/12/unit-test-network-layer-in-ios/

vinhnx commented 6 years ago

Check https://github.com/vinhnx/iOS-notes/issues/47 on how to build a generic Moya network request.