Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a mock data object for unit testing

Currently I'm trying to unit test a function that takes in a parameter that is a data object:

addColor(_ coreDataManagerContext: NSManagedObjectContext, _ object: Color?) {//code here}

The issue is that it takes in an object: Color? that needs to be mocked. Here is what the original Color model looks like, it's parsed in Swift 4 :

class Color: Codable {

    var id: String
    var name: String


    enum CodingKeys: String, CodingKey {
        case id = "Id"
        case name = "Name"

    }
}

I thought about doing something like this:

class mockColorObject: Color {

   self.name = "red"//error here
}

but get the error: "expected declaration"

like image 797
SwiftyJD Avatar asked May 13 '26 07:05

SwiftyJD


1 Answers

You probably want to set this variable in an initializer:

class mockColorObject: Color {

    required init(from decoder: Decoder) throws {
        try super.init(from: decoder)
        self.name = "red"
    }
}

However, if you can change the code being tested, it might be a better strategy to define a ColorType protocol that Color and mockColorObject both conform to, since subclassing for the purpose of mocking can lead to problems.

like image 153
Luke Avatar answered May 15 '26 08:05

Luke



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!