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
}
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
}
2
Answers
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…
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.
You cannot test what the UUID is. Just test that the newly instantiated object has a UUID and walk away. To do more would imply that you are testing UUID itself, and that would be wrong — it’s not the subject-under-test and doesn’t belong to you.
(And in general do not aim for / expect 100% coverage. That’s insane. 80% is a good goal.)