Should We Write Unit Tests for Network Classes?

Saeid Rezaeisadrabadi
2 min readJun 26, 2022

In this Story, I want to show a simple unit test for a network class and talk about writing Unit-tests for them.

For any kind of component, if there is a logic or behavior that you want to test, make sure there is a unit test for it.
When it comes to the network layer, it is not significantly different from the view model if it contains behaviors.

Does the network layer have any logic?
In the network layer, we map API responses to our model.
Therefore, we write unit tests to ensure that our mapping logic works when we receive a valid API response.

Some scenarios for testing:

  • Convert string date into date object
  • Handle null values
  • Specify correct data type for each property

I prepare a simple unit test for my network class in this project.

final class ComputerAPITests: XCTestCase { var sut: ComputerAPIProtocol!
var apiRequestMock: APIRequestProtocol!
override func setUpWithError() throws {
apiRequestMock = APIRequestProtocolMock()
sut = ComputerAPI(apiRequest: apiRequestMock)
}
func testDecodeResponse() async throws {
let response = try await sut.fetchRandomComputer()
XCTAssertNotNil(response)
}
}

I created a mock class for my `APIRequestProtocol` because I don’t want to test URL-session ( apple test it well ).

final class APIRequestProtocolMock: APIRequestProtocol { private enum Constants {
static let successResponse = "Based on your api and model"
}
func get(request: URLRequest) async throws -> Result<Data, Error> {
return .success(Constants.successResponse.data(using: .utf8)!)
}
}

If you want to read more about network implementation, you can read this story.

There you are! Perhaps writing unit tests for network classes aren’t worth it, as the logic is too simple, but on the other hand, it doesn’t take too much time, so I recommend writing unit tests for every component.

--

--