Home > Mobile >  How to initialize WidgetInfo for unit testing in Xcode?
How to initialize WidgetInfo for unit testing in Xcode?

Time:06-07

I am trying to initialize the WidgetKit struct WidgetInfo for unit testing a function that takes WidgetInfo as an argument:

let widgetInfo = WidgetInfo()

This gives me the error: 'WidgetInfo' cannot be constructed because it has no accessible initializers

I tried adding:

extension WidgetInfo {
    public init() {}
}

and I can initialize - yay! But then I try to set one of its properties

widgetInfo.family = .systemSmall

and get the error: Cannot assign to property: 'family' is a 'let' constant

I tried another initializer with arguments:

extension WidgetInfo {
    public init(family: WidgetFamily, kind: String) {
        self.family = family
        self.kind = kind
    }
}

and I get the error: 'let' property 'family' may not be initialized directly; use "self.init(...)" or "self = ..." instead

I'm stuck - is there a way for me to initialize WidgetInfo? Or another way to test a function that takes WidgetInfo as an argument?

CodePudding user response:

Figured it out. I created a WidgetInfo protocol with the information I needed, changed the function to take the protocol as the argument and extended WidgetInfo:

protocol WidgetInfoProtocol {
    var widgetFamily: WidgetFamily { get }
    var widgetKind: String { get }
}

extension WidgetInfo: WidgetInfoProtocol {
    var widgetFamily: WidgetFamily {
        return family
    }

    var widgetKind: String {
        return kind
    }
}

This allowed me to create a mock for use in unit testing:

struct MockWidgetInfo: WidgetInfoProtocol {
    var widgetFamily: WidgetFamily
    var widgetKind: String
}
  • Related