<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Alejandro Gelos on Medium]]></title>
        <description><![CDATA[Stories by Alejandro Gelos on Medium]]></description>
        <link>https://medium.com/@alejandrogelos?source=rss-2a5d7e10267d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*t4tlTjNzPAtxvDDxhV0VPw@2x.jpeg</url>
            <title>Stories by Alejandro Gelos on Medium</title>
            <link>https://medium.com/@alejandrogelos?source=rss-2a5d7e10267d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 15:38:52 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@alejandrogelos/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Your iOS Network Layer Should Be Boring]]></title>
            <link>https://medium.com/@alejandrogelos/your-ios-network-layer-should-be-boring-3e66a89a7c99?source=rss-2a5d7e10267d------2</link>
            <guid isPermaLink="false">https://medium.com/p/3e66a89a7c99</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[ios-apps]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Alejandro Gelos]]></dc:creator>
            <pubDate>Sun, 17 May 2026 21:20:03 GMT</pubDate>
            <atom:updated>2026-05-20T13:44:59.706Z</atom:updated>
            <content:encoded><![CDATA[<p>Network code should be easy to understand.</p><p>Not clever.</p><p>Not magical.</p><p>Just clear.</p><p>But as the app grows, the Network Layer usually grows with it.</p><p>More endpoints, headers, DTOs, mapping, tests, and duplicated code.</p><p>Without structure, it becomes a snowball.</p><p>Changing one endpoint starts to feel risky, debugging takes longer, and nobody is completely sure where each responsibility lives.</p><blockquote><a href="https://github.com/alegelos/iOSCleanNetwork">iOSCleanNetwork</a> exists to avoid that by giving every piece one clear job.</blockquote><h3>The Goal</h3><p><a href="https://github.com/alegelos/iOSCleanNetwork">iOSCleanNetwork</a> is not about making networking fancy.</p><p>It is about making the Network Layer predictable:</p><pre>Setup      → defines the request<br>Provider   → executes, decodes, and maps<br>DTO        → data transferred through the API boundary<br>Domain     → protocols and models used by the app<br>Mapper     → converts transport data into Domain<br>Session    → external boundary</pre><p>When the structure is consistent, adding or changing an endpoint becomes much easier to follow.</p><h3>The Structure</h3><p>The full idea:</p><pre>Feature / Use Case / ViewModel<br>            │<br>            ▼<br>      Domain Protocol<br>            │<br>            ▼<br>        Provider<br>            │<br>            ▼<br>          Setup<br>            │<br>            ├── Path<br>            ├── Method<br>            ├── Headers<br>            ├── Query Items<br>            └── DTO To Send<br>            │<br>            ▼<br>         Session<br>            │<br>            ├── URLSession.shared in Production<br>            └── MockedURLSession in Tests<br>            │<br>            ▼<br>       DTO From API<br>            │<br>            ▼<br>          Mapper<br>            │<br>            ▼<br>       Domain Model</pre><p>That separation is what keeps the Network Layer clean.</p><h3>Domain Defines the Contract</h3><p>Domain should stay simple.</p><p>Protocols and Models</p><p>For example:</p><pre>Domain<br>├── Providers<br>│   └── BooksProvider<br>│       ├── BooksProviderProtocol<br>│       └── SearchBooksResult<br>│<br>└── Models<br>    └── Book</pre><p>The provider protocol defines what the feature needs.</p><pre>protocol BooksProviderProtocol {<br>    func searchBooks(query: String) async throws -&gt; SearchBooksResult<br>}</pre><p>Provider-specific models live next to that provider.</p><pre>struct SearchBooksResult: Equatable {<br>    let books: [Book]<br>    let nextPage: Int?<br>}</pre><p>Shared models live in Domain/Models.</p><pre>struct Book: Equatable {<br>    let id: String<br>    let title: String<br>    let author: String<br>}</pre><p>Domain is the heart of the app.</p><p>Data depends on Domain by implementing its provider protocols.</p><p>Presentation depends on Domain by using its models and contracts.</p><h3>Setup Defines the Request</h3><p>A Setup owns the request configuration.</p><p><a href="https://github.com/alegelos/iOSCleanNetwork">iOSCleanNetwork</a> gives you ApiSetupProtocol.</p><p>Your concrete setup conforms to it.</p><pre>import Foundation<br>import iOSCleanNetwork<br><br>enum BooksAPISetup: ApiSetupProtocol {<br>    case searchBooks(<br>        baseURL: URL,<br>        query: String<br>    )<br><br>    var request: URLRequest {<br>        get throws {<br>            let baseURL: URL<br><br>            switch self {<br>            case let .searchBooks(url, _):<br>                baseURL = url<br>            }<br><br>            let fullURL = baseURL.appendingPathComponent(path)<br><br>            guard var components = URLComponents(<br>                url: fullURL,<br>                resolvingAgainstBaseURL: false<br>            ) else {<br>                throw ApiErrors.invalidUrl<br>            }<br><br>            components.queryItems = queryItems<br><br>            guard let url = components.url else {<br>                throw ApiErrors.invalidUrl<br>            }<br><br>            var request = URLRequest(url: url)<br>            request.httpMethod = method.rawValue<br><br>            for (field, value) in try headers {<br>                request.setValue(value, forHTTPHeaderField: field)<br>            }<br><br>            request.httpBody = body<br><br>            return request<br>        }<br>    }<br><br>    var path: String {<br>        &quot;books/search&quot;<br>    }<br><br>    var method: HttpMethod {<br>        .get<br>    }<br><br>    var headers: [String: String] {<br>        get throws {<br>            [<br>                &quot;Accept&quot;: &quot;application/json&quot;<br>            ]<br>        }<br>    }<br><br>    var queryItems: [URLQueryItem] {<br>        switch self {<br>        case let .searchBooks(_, query):<br>            return [<br>                URLQueryItem(name: &quot;q&quot;, value: query)<br>            ]<br>        }<br>    }<br><br>    var body: Data? {<br>        nil<br>    }<br>}</pre><p>A Setup should only describe the request.</p><p>It does not execute, decode, or map anything.</p><p>When you add a new endpoint, you add a new case to the setup enum:</p><pre>enum BooksAPISetup: ApiSetupProtocol {<br>    case searchBooks(baseURL: URL, query: String)<br>    case bookDetails(baseURL: URL, bookID: String)<br>}</pre><p>ApiSetupProtocol forces you to complete the missing setup for the new endpoint.</p><h3>Provider Executes the Flow</h3><p>A Provider owns the request execution.</p><p><a href="https://github.com/alegelos/iOSCleanNetwork">iOSCleanNetwork</a> gives you NetworkSessionProtocol.</p><p>That means your provider can use URLSession.shared in production and another session in tests.</p><pre>import Foundation<br>import iOSCleanNetwork<br><br>final class BooksAPIProvider: BooksProviderProtocol {<br>    private let baseURL: URL<br>    private let session: any NetworkSessionProtocol<br><br>    init(<br>        baseURL: URL,<br>        session: any NetworkSessionProtocol = URLSession.shared<br>    ) {<br>        self.baseURL = baseURL<br>        self.session = session<br>    }<br><br>    func searchBooks(query: String) async throws -&gt; SearchBooksResult {<br>        let setup = BooksAPISetup.searchBooks(<br>            baseURL: baseURL,<br>            query: query<br>        )<br><br>        let (data, _) = try await session.data(for: setup)<br><br>        let dto = try JSONDecoder().decode(<br>            SearchBooksResultDTO.self,<br>            from: data<br>        )<br><br>        return dto.domain<br>    }<br>}</pre><p>The flow stays small:</p><pre>Provider<br>   ↓<br>Setup<br>   └── DTO to send / body<br>   ↓<br>Session<br>   ↓<br>DTO from API<br>   ↓<br>Mapper<br>   ↓<br>Domain</pre><p>The Provider bridges the API world and the app world, returning Domain models instead of raw transport data.</p><h3>DTOs Belong to the API Boundary</h3><p>DTO means Data Transfer Object.</p><p>A DTO represents data that crosses the API boundary.</p><p>It can be sent to the API:</p><pre>struct SearchBooksDTO: Encodable {<br>    let query: String<br>}</pre><p>It can also be received from the API:</p><pre>struct SearchBooksResultDTO: Decodable {<br>    let items: [BookDTO]<br>    let nextPage: Int?<br>}<br><br>struct BookDTO: Decodable {<br>    let id: String<br>    let title: String<br>    let authorName: String<br><br>    enum CodingKeys: String, CodingKey {<br>        case id<br>        case title<br>        case authorName = &quot;author_name&quot;<br>    }<br>}</pre><p>DTOs are based on the API contract.</p><p>They stay in Data.</p><p>Domain models stay in Domain.</p><h3>Mapping Converts DTOs into Domain</h3><p>The mapper converts transport data into app data.</p><p><a href="https://github.com/alegelos/iOSCleanNetwork">iOSCleanNetwork</a> does not force a special mapper type.</p><p>A simple approach is to keep a domain computed property close to the DTO that owns the API shape.</p><pre>extension SearchBooksResultDTO {<br>    var domain: SearchBooksResult {<br>        SearchBooksResult(<br>            books: items.map(\.domain),<br>            nextPage: nextPage<br>        )<br>    }<br>}<br><br>extension BookDTO {<br>    var domain: Book {<br>        Book(<br>            id: id,<br>            title: title,<br>            author: authorName<br>        )<br>    }<br>}</pre><p>If the backend changes, update the DTO or mapper.</p><p>If the feature changes, update the Domain model or mapper.</p><h3>Authentication Stays Outside</h3><p><a href="https://github.com/alegelos/iOSCleanNetwork">iOSCleanNetwork</a> is authentication-agnostic.</p><p><a href="https://github.com/alegelos/iOSCleanNetwork">iOSCleanNetwork</a> gives you ApisGatewayProtocol.</p><p>Your app decides how tokens are obtained.</p><p>That can be OAuth, AppAuth, or any other token provider.</p><pre>import iOSCleanNetwork<br><br>final class AppGateway: ApisGatewayProtocol {<br>    func apisAccessToken(policy: AccessTokenPolicy) async throws -&gt; String {<br>        switch policy {<br>        case .useCache:<br>            return &quot;cached-access-token&quot;<br>        case .forceRefresh:<br>            return &quot;refreshed-access-token&quot;<br>        }<br>    }<br>}</pre><p>Then a provider can use the unauthorized retry helper:</p><pre>let (data, _) = try await session.dataWithUnauthorizedRefreshRetry(<br>    apiAccessProvider: apiAccessProvider,<br>    buildEndpoint: { accessToken in<br>        BooksAPISetup.searchBooks(<br>            baseURL: baseURL,<br>            query: query<br>        )<br>    }<br>)</pre><p>The framework coordinates the retry boundary.</p><p>Your app owns the authentication strategy.</p><h3>Testing Uses the Same Provider</h3><p>Testing is not the main goal of the structure.</p><p>It is a consequence.</p><p>iOSCleanNetworkTesting gives you MockedURLSession.</p><p>In production:</p><pre>let provider = BooksAPIProvider(<br>    baseURL: baseURL,<br>    session: URLSession.shared<br>)</pre><p>In tests:</p><pre>let provider = BooksAPIProvider(<br>    baseURL: baseURL,<br>    session: MockedURLSession()<br>)</pre><p>The Provider does not change.</p><p>The test still runs through:</p><pre>same Provider<br>same Setup<br>same Decoding<br>same Mapper<br>same Domain model</pre><p>Only the session changes.</p><p>The test is not validating a fake Provider.</p><p>It is validating the real integration flow with a controlled JSON fixture.</p><p>Broken decoding, wrong mapping, or invalid response assumptions can fail before production.</p><h3>Fixtures Connect Through the Setup</h3><p>For fixture-based tests, iOSCleanNetworkTesting gives you URLSessionSetupProtocol.</p><p>You extend your existing Setup in the test target and provide the JSON file name.</p><pre>import iOSCleanNetworkTesting<br><br>extension BooksAPISetup: URLSessionSetupProtocol {<br>    var jsonFileName: String {<br>        switch self {<br>        case .searchBooks:<br>            return &quot;searchBooks&quot;<br>        }<br>    }<br>}</pre><p>Then MockedURLSession can load the right JSON fixture for the same setup used by production.</p><p>No test-only Provider, no duplicated request logic, only sample JSON.</p><h3>Spies Are for Orchestration Tests</h3><p>MockedURLSession is for testing the transport flow.</p><p>Spies solve a different problem.</p><p>iOSCleanNetworkTesting gives you ProviderSpyProtocol.</p><p>Use it when a higher-level service calls one or more providers and you want to verify the orchestration.</p><pre>import iOSCleanNetworkTesting<br><br>final class BooksProviderSpy: ProviderSpyProtocol {<br>    enum MethodKey: String, Hashable, CaseIterable {<br>        case searchBooks<br>    }<br><br>    var invocationsCount: [MethodKey: Int] = [:]<br>    var failingMethos: [(method: MethodKey, error: Error)] = []<br><br>    private let wrappedProvider: any BooksProviderProtocol<br><br>    init(wrapping wrappedProvider: any BooksProviderProtocol) {<br>        self.wrappedProvider = wrappedProvider<br>    }<br>}</pre><p>Then the spy forwards the call to the real provider:</p><pre>extension BooksProviderSpy: BooksProviderProtocol {<br>    func searchBooks(query: String) async throws -&gt; SearchBooksResult {<br>        increment(.searchBooks)<br>        try validateFailingMethods(method: .searchBooks)<br><br>        return try await wrappedProvider.searchBooks(query: query)<br>    }<br>}</pre><p>That keeps service-level tests readable without replacing the real provider logic everywhere.</p><h3>AI-Ready by Design</h3><p><a href="https://github.com/alegelos/iOSCleanNetwork">iOSCleanNetwork</a> also includes an AI-ready README.</p><p>Share the repository with your AI agent and ask for things like:</p><pre>add this new endpoint using iOSCleanNetwork.</pre><p>Or:</p><pre>Refactor my Network Layer to follow the iOSCleanNetwork structure.</pre><p>So AI can follow the structure without you explaining it from scratch.</p><h3>Why This Helps When the App Grows</h3><p>Adding a new endpoint should feel familiar:</p><pre>create or update the Domain protocol<br>create the Domain model<br>create the DTO to send<br>create the DTO from API<br>map DTO to Domain<br>add the Setup case<br>add the Provider method<br>add the JSON fixture<br>write the test</pre><p>That consistency reduces duplicated code and keeps the Network Layer easier to review, debug, and extend.</p><p>It also helps new developers understand the project faster.</p><h3>Final Thought</h3><p>A good Network Layer should be boring.</p><p>You should be able to open the project and quickly understand where everything lives.</p><p>That is what <a href="https://github.com/alegelos/iOSCleanNetwork">iOSCleanNetwork</a> tries to make easy:</p><p>clean networking through a simple, predictable structure.</p><p>Github repo: <a href="https://github.com/alegelos/iOSCleanNetwork">https://github.com/alegelos/iOSCleanNetwork</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3e66a89a7c99" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stop Mocking the Code You Should Be Testing]]></title>
            <link>https://medium.com/@alejandrogelos/stop-mocking-the-code-you-should-be-testing-9b2b2533742d?source=rss-2a5d7e10267d------2</link>
            <guid isPermaLink="false">https://medium.com/p/9b2b2533742d</guid>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Alejandro Gelos]]></dc:creator>
            <pubDate>Fri, 08 May 2026 17:12:30 GMT</pubDate>
            <atom:updated>2026-05-20T13:42:12.967Z</atom:updated>
            <content:encoded><![CDATA[<h3>Stop Mocking the Code You Should Be Testing</h3><h3>The Real Problem</h3><p>Imagine <strong>AI modifies a JSON decoding key</strong> 🤖</p><p>Tests still pass ✅, but the app is now <strong>broken in production</strong> 💥</p><p>You cannot write isolated tests for <strong>every tiny part of the code</strong>. <br>That <strong>does not scale</strong> 📉</p><p>The goal is simple: <strong>save time</strong>, <strong>keep things simple</strong>, and make developers <strong>more productive</strong> 🚀</p><p><strong>Mock less, less interfaces, less tests, less code to maintain.<br>Reduce the number of bugs that slip through.</strong> 🧹</p><p>With this approach, that broken change would be caught by the existing flow test. 🎯</p><p>Any change that <strong>break production</strong>, should <strong>fail before it reaches production.</strong></p><h3>Introduction</h3><p>In many mobile projects, ViewModel tests end up testing mocks instead of behavior.</p><p>We create a MockService, return a predefined model, inject it into the ViewModel, call a method, and assert that the expected state was published.</p><p>The test passes. ✅<br> Coverage goes up. 📈<br> But confidence does not always follow. ⚠️</p><p>Because in many cases, the mock skipped the parts that usually break:</p><pre>- request setup<br>- JSON decoding<br>- response mapping<br>- real API-shaped data<br>- ViewModel state transitions<br>- unexpected callbacks or side effects</pre><p>It can feel like writing the answer on the back of a card, flipping it, and celebrating because we got it right. 🃏</p><p>The goal is not to mock the feature.</p><p>The goal is simpler:</p><blockquote><em>Test the real ViewModel, the real Provider, and the real mapping.<br> Replace only the external boundary.</em></blockquote><h3>The Core Idea</h3><p>Keep the feature real.<br> Replace the boundary.</p><p>For a network-driven feature, the external boundary is usually the HTTP client: `URLSession` on iOS or `OkHttpClient` on Android.</p><pre>                        ViewModel  <br>                            │<br>                            │ use injected dependency <br>                            │<br>                            ▼<br>                 FirebaseLoginAPIProvider<br>                            │ <br>                            │ builds request <br>                            │<br>                            │ use injected dependency<br>                            │<br>                            ▼<br>                  NetworkSessionProtocol<br>                            │<br>           production       │           test<br>              ┌─────────────┴─────────────┐<br>              ▼                           ▼<br>Real URLSession/OkHttpClient      Mocked URLSession/OkHttpClient<br>              │                           │<br>              ▼                           ▼<br>        Backend JSON                 Local JSON<br>              │                           │<br>              └─────────────┬─────────────┘<br>                            │<br>                            │ response data<br>                            │<br>                            ▼<br>                 FirebaseLoginAPIProvider<br>                            │<br>                            │ decode to FirebaseLoginDTO<br>                            │ map to Domain Model<br>                            │<br>                            ▼<br>                        ViewModel</pre><p>Same ViewModel.<br> Same Domain contract.<br> Same Provider.<br> Same decoding.<br> Same mapping.<br> Only the boundary changes.</p><h3>Clean Architecture Helps</h3><p>This approach fits naturally with Clean Architecture.</p><p>The important rule is:</p><blockquote><em>Presentation and Data depend on Domain.<br> Domain does not depend on either.</em></blockquote><pre>Presentation<br> └── Modules (Views)<br>      ├── Login<br>      │    ├── View<br>      │    └── ViewModel<br>      ├── Profile<br>      │    ├── View<br>      │    └── ViewModel<br>      └── Orders<br>           ├── View<br>           └── ViewModel<br>                │<br>                ▼<br>Domain<br> ├── Models<br> └── Service interfaces<br>                ▲<br>                │<br>Data<br> ├── Networking<br> │    └── iOSCleanNetwork<br> │         ├── ApiSetupProtocol (Endpoint configuration)<br> │         └── NetworkSessionProtocol (URLSession/OkHttpClient abstraction)<br> │<br> └── APIs<br>      ├── FirebaseLoginAPI<br>      │    ├── FirebaseLoginAPISetup<br>      │    ├── FirebaseLoginAPIProvider<br>      │    └── DTOs<br>      │         └── FirebaseLoginDTO<br>      │              └── Mapper to Domain Model<br>      │<br>      └── StripePaymentsAPI<br>           ├── StripePaymentsAPISetup<br>           ├── StripePaymentsAPIProvider<br>           └── DTOs<br>                └── StripePaymentDTO<br>                     └── Mapper to Domain Model</pre><p>Domain defines what the feature needs.<br> Data decides how to provide it.<br> Presentation consumes it through the ViewModel.</p><p>That separation is what lets us replace the external dependency without replacing the feature itself.</p><h3>Testing the ViewModel State</h3><p>Once the Provider can run against controlled data, the ViewModel can be tested with a more realistic flow.</p><p>A good ViewModel test should verify more than the final value.</p><p>It should verify the state around it:</p><pre>- loading starts when the action begins<br>- loading stops when the action finishes<br>- the expected value is assigned<br>- the error state remains empty<br>- unrelated values do not change<br>- unexpected callbacks are not triggered</pre><p>Bugs are not always in the final value.</p><p>Sometimes the value is correct, but the state around it is wrong.</p><h3>Where iOSCleanNetwork Fits</h3><p>This idea becomes easier when the network layer is designed around replaceable boundaries.</p><p>That is the reason behind <a href="https://medium.com/@alejandrogelos/your-ios-network-layer-should-be-boring-3e66a89a7c99">iOSCleanNetwork</a>.</p><p><a href="https://medium.com/@alejandrogelos/your-ios-network-layer-should-be-boring-3e66a89a7c99">iOSCleanNetwork</a> provides a simple interface to quickly build a clean network layer following the ideas from this article.</p><p>It helps keep request setup, provider logic, DTOs, mapping, and HTTP client handling separated, so the network code stays easier to test and replace.</p><p><a href="https://medium.com/@alejandrogelos/your-ios-network-layer-should-be-boring-3e66a89a7c99">Here is the complete article about iOSCleanNetwork.</a></p><h3>The Structure Is What Matters</h3><p>The idea is not just “mock URLSession or OkHttpClient”.</p><p>The real goal is to organize the code around clear responsibilities, so each piece has a defined place and the feature can grow without becoming fragile.</p><blockquote>When responsibilities are mixed, the code starts turning into spaghetti. One thing in the wrong place becomes a snowball effect: logic leaks everywhere, the flow becomes harder to follow, and small changes start creating random bugs.</blockquote><p>Good structure makes the code easier to read, maintain, and evolve. It also makes proper testing possible, because we can validate the real feature behavior without replacing the code we should actually trust.</p><p>That is the balance this article is about:</p><p>well-organized code that behaves as expected, and tests that validate the real flow instead of testing mocks.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9b2b2533742d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>