Search code examples
swiftstructxctestswift-protocolsxctestcase

How can I assert a struct conforms to a protocol?


I have a test case that asserts a class conforms to a protocol.

        let sut = SomeClass()    
        ..........
        func test_some_class_conform_to_protocol() {
                XCTAssertTrue((sut as Any) is OverlayManagerType)

        }

I am trying to implement the same test with a struct that conforms to a protocol, however the test constantly fails.

Is it possible to achieve this?

EDIT

I have added my struct. I am following a TDD approach so there is no implementation as of yet.

protocol CountManagerType {

}

struct CountManager: CountManagerType {

}

My test is

    func test_count_manager_conform_to_protocol() {
            XCTAssertTrue((sut as Any) is CountManagerType)

    }

Solution

  • Your code works fine for me, in the following example

    protocol CountManagerType {
    }
    struct CountManager1: CountManagerType {
    }
    struct CountManager2 {
    }
    
    let c1 = CountManager1()
    print(((c1 as Any) is CountManagerType)) // true
    let c2 = CountManager2()
    print(((c2 as Any) is CountManagerType)) // false