Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Struct property initialization testing

XCTest code coverage indicates that I should make a test for HealthStat's id property initialization. What is the best way to test it?

struct HealthStat: Identifiable {
    let id = UUID()
    let stat: HKQuantity?
    let date: Date
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

What is it that you are trying to test about it? With the current implementation it would be fairly hard to test anything about it as you have no control over what the value of the UUID is. In order to improve the testability you would have to inject the creation of the UUID (or the UUID itself).

For instance, you could update your code to something like…

struct HealthStat: Identifiable {
  let id: UUID
  let stat: HKQuantity?
  let date: Date

  init(id: UUID = UUID(), stat: HKQuantity?, date: Date) {
    self.id = id
    self.stat = stat
    self.date = date
  }
}

Now you can test that whatever id you pass into the model is stored in the id. But also, in production code it will get a default UUID created using UUID().

But there are infinitely many varieties of how to test this sort of thing.

I guess this is the most basic version of dependency injection. The dependency in this case is the creation of UUIDs. And you have to inject it in order to make it testable.

Search for Swift Dependency Injection to read more about what it can do for you.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading