Home > Enterprise >  Swift 5: I have a problem when I try to instantiate a viewmodel for testing
Swift 5: I have a problem when I try to instantiate a viewmodel for testing

Time:02-16

I'm trying to instantiate my viewmodel for testing, in this case I don't need its parameters, but as it asks me to add them, when I try I get an error "Constant 'data' used before being initialized"

This is my code:

struct Account: Codable {
    let details: [Details]?

}

struct Details: Codable {
    let id: String?
    let currency: String?
    let interest: Float64?
    let date: String?
}
class DetailViewModel {

    private let data: Details?
    
    init(data: Details) {
        self.data = data
    }
}

Tests:

class DetailViewModelTest: QuickSpec {
    override func spec() {
                
        var viewModel : DetailViewModel!
        let data: Details!
        viewModel = DetailViewModel(data: data) // I have error in this line
  }
}

Is there a way to instantiate my viewmodel without parameters? Or a better way to handle this?

CodePudding user response:

To use Details in a test with hardcoded values you either need to create it from some json or add another init to initialise all values, here I am using the latter. I am adding it in an extension and created a static method that uses the init to create an object with hard coded values.

extension Details {
    private init(id: String, currency: String, interest: Float64, date: String) {
        self.id = id
        self.currency = currency
        self.interest = interest
        self.date = date
    }

    static func createStub() -> Details {
        Details(id: "1", currency: "EUR", interest: 1.23, date: "2022-02-12")
    }
}

This is one way of doing it, the init could be designed in many ways but this is to show you how to move forward.

This can then be used in the test class

class DetailViewModelTest: QuickSpec {
    override func spec() {
        let viewModel = DetailViewModel(data: Details.createStub())
    //...
    }
}

CodePudding user response:

you should:

let data: Details = Details() // create your data
  • Related