首页 > 解决方案 > 如何断言结构符合协议?

问题描述

我有一个测试用例断言一个类符合协议。

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

        }

我正在尝试使用struct符合协议的 a 来实现相同的测试,但是测试不断失败。

有可能实现这一目标吗?

编辑

我已经添加了我的结构。我正在遵循 TDD 方法,因此目前还没有实现。

protocol CountManagerType {

}

struct CountManager: CountManagerType {

}

我的测试是

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

    }

标签: swiftstructxctestswift-protocolsxctestcase

解决方案


在以下示例中,您的代码对我来说很好

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

推荐阅读