Skip to content

Latest commit

 

History

History
68 lines (44 loc) · 2.71 KB

fakeable.md

File metadata and controls

68 lines (44 loc) · 2.71 KB

Fakeable

Instantiating models for tests is not a simple task. Sometimes, the initializer has too many attributes and the test does not rely on the full set of attributes. This inconvenience hurts our ability to efficiently unit test our app, which could discourage members from writing them at all.

To help with this, we have introduced a new framework called Fakes.framework. This framework defines .fake() functions for all of our networking models. The .fake() function instantiates a type with fake values. As of now, we are defining fake values as empty values.

This, in conjunction with the copiable pattern allow us to write tests like:

func test() {
     // Given
     let initialProduct = Product.fake()
     let expectedProduct = initialProduct.copy(name: "new-name")
     let ViewModel = ViewModel(product: initialProduct)

     // When
     viewModel.updateName("new_name")

     // Then
     XCTAssertEqual(viewModel.product, expectedProduct)
}

Note: This framework is meant to be used in test targets only!

Generating Fake Methods

The fake() methods are generated using Sourcery. For now, only classes, structs, and enums of the Networking and Yosemite target are supported.

To generate a fake() method:

  1. Make it conform to GeneratedFakeable.

    import Codegen
    
    struct ProductSettings: GeneratedFakeable {
        ...
    }
  2. In the terminal, navigate to the project's root folder and run rake generate.

    $ cd /path/to/root
    $ rake generate
    

    This will update the Fakes.generated file with the new fake() method.

  3. Compile the project.

Modifying The Fakeable Code Generation

The rake generate command executes the Sourcery configuration files located in the CodeGeneration/Sourcery/Fakes folder.

Networking module → Networking-Fakes.yaml
Yosemite module → Yosemite-Fakes.yaml

It uses a single template, Fakes.swifttemplate, to generate the code. It's written using Swift templates.

Please refer to the Sourcery reference for more info about how to write templates.