Creating CLPlacemark with custom values for testing
Asked Answered
F

2

6

I have an application that moves CLPlacemark objects around and uses them, and I would like to unit-test several components that interact with them. To do this, I would like to be able to stub out calls to real reverse-geolocation from MapKit with methods that produce mock CLPlacemarks with known values.

CLPlacemark only has one initializer (copy initializer). But in the documentation, it says:

Placemark objects are typically generated by a CLGeocoder object, although you can also create them explicitly yourself.

However, most of the members are read-only, so I'm not sure how to create one with custom values. Is it possible to set internal properties in this way in Swift? If not, any ideas as to what they mean in the above citation?

Friesian answered 13/4, 2016 at 21:9 Comment(0)
O
0

I would use OCMock (http://ocmock.org) to stub out calls to create stub CLPlacemark objects, and stub out their getter methods with your own values.

id userDefaultsMock = OCMClassMock([CLPlacemark class]);

// set it up to return a specific value when stringForKey: is called
OCMStub([userDefaultsMock property]).andReturn(customValue);
Osborne answered 13/4, 2016 at 21:29 Comment(1)
thanks for that suggestion. I have been avoiding use of OCMock because it's strictly designed with ObjcC in mind, but I bet I can find my own way (i.e. subclasses or something) to stub out property getters.Friesian
T
1

Some archeology here, but here is a working answer, as I just had this need

    public static func mock(coordinate: CLLocationCoordinate2D, name: String) -> CLPlacemark {
        let mkPlacemark = MKPlacemark(
            coordinate: coordinate,
            addressDictionary: ["name": name]
        )
        return CLPlacemark(placemark: mkPlacemark)
    }

Usage:

let placemark = CLPlacemark.mock(
    coordinate: CLLocation(latitude: 0, longitude: 0), name: "mock-name"
)
Treacy answered 17/10, 2023 at 13:24 Comment(0)
O
0

I would use OCMock (http://ocmock.org) to stub out calls to create stub CLPlacemark objects, and stub out their getter methods with your own values.

id userDefaultsMock = OCMClassMock([CLPlacemark class]);

// set it up to return a specific value when stringForKey: is called
OCMStub([userDefaultsMock property]).andReturn(customValue);
Osborne answered 13/4, 2016 at 21:29 Comment(1)
thanks for that suggestion. I have been avoiding use of OCMock because it's strictly designed with ObjcC in mind, but I bet I can find my own way (i.e. subclasses or something) to stub out property getters.Friesian

© 2022 - 2024 — McMap. All rights reserved.