有没有相当于检查在swift语言中抛出异常单元测试?
例如我有一个类:
class Square : NSObject{ let sideLength: Int init(sideLength: Int) { assert(sideLength >= 0,"Wrong initialization of Square class with below zero side length") self.sideLength = sideLength super.init() } }
和测试检查它的工作.在目标C中,我可以这样写测试方法:
- (void)testInitializationWithWrongSideLengthThrowsExceptions{ XCTAssertThrows([[Shape alloc] initWithSideLength: -50],"Should throw exceptions on wrong side values initialisations"); }
什么是Swift等技术?
我认为assert() – 函数只能用于调试目的.不仅仅是因为苹果Swift-Book(
https://itun.es/de/jEUH0.l)的以下声明:
原文链接:https://www.f2er.com/swift/319851.html“断言导致您的应用程序终止,并不能代替设计您的代码,使得无效的条件不太可能出现.”
这就是为什么我会解决如下:
import Cocoa import XCTest class Square { let sideLength: Int init(_ sideLength: Int) { self.sideLength = sideLength >= 0 ? sideLength : 0 } } class SquareTests: XCTestCase { override func setUp() { super.setUp() } override func tearDown() { super.tearDown() } func testMySquareSideLength() { let square1 = Square(1); XCTAssert(square1.sideLength == 1,"Sidelength should be 1") let square2 = Square(-1); XCTAssert(square2.sideLength >= 0,"Sidelength should be not negative") } } let tester = SquareTests() tester.testMySquareSideLength()