Testing if an object implements the protocol
Using a unit testing system,
var car: IVehicle = Vehicle.getInstance("mycar") //dictionary
XCTAssertNotNil(car, "Expecting instance not null")
didn't work, not sure why (results in compiler error "IVehicle do not conform to AnyObject protocol").
But car as Car
worked:
XCTAssertNotNil(car as Car, "Expecting instance not null")
It didn't work saying that the test is always right, not sure how can we check if the protocol matches?
XCTAssertTrue(car is IVehicle, "Expecting instance implements IVehicle")
source to share
Firstly,
XCTAssertNotNil(car, "Expecting instance not null")
Assuming what IVehicle
is a protocol, the error you get is that it means that it is not AnyObject
what is required XCTAssertNotNil
as the first parameter ( AnyObject
can only represent classes, not structures or protocols). This is perhaps a little disappointing because it XCTAssertNotNil
assumes it's meant to be tested if optionsals are set to nil, but there you have it.
Further:
XCTAssertNotNil(car as Car, "Expecting instance not null")
This compiles, but it probably hasnt "worked" ... if car
never car
, you will get a runtime exception, not an assertion rejection. This is because it car as Car
forces the compiler to treat the left expression as right, whether or not it is (assuming this is a valid action, at least in some circumstances - if it is not possible at all, youll get a compiler error). If this is not a valid listing at runtime, you will get a runtime failure.
A safe way to cast car
to car
if you are not sure has as?
. So this should give you the results you want:
XCTAssertNotNil(car as? Car, "Expecting instance not null")
This will result in Some(car)
if it is valid car
or nil
, if it is not, correctly triggering the test assertion.
Alternatively, you can simply write:
XCTAssert(car is Car, "Expecting car to be a Car")
Finally,
car is IVehicle
always true because the compiler knows the type of the car variable at compile time and knows perfectly well that it IVehicle
is its type. Therefore, it is assumed that you wrote it by accident, as it cannot ever be false and that tells you so.
source to share