使用XCTAssertThrows模拟进行Swift单元测试

Nik*_*kov 17 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()
    }
}
Run Code Online (Sandbox Code Playgroud)

和测试检查它的工作.在目标CI中可以编写如下测试方法:

- (void)testInitializationWithWrongSideLengthThrowsExceptions{
   XCTAssertThrows([[Shape alloc] initWithSideLength: -50], "Should throw exceptions on wrong side values initialisations");
}
Run Code Online (Sandbox Code Playgroud)

什么是Swift等技术?

How*_*att 2

如果将以下三个文件添加到测试中:

//  ThrowsToBool.h
#import <Foundation/Foundation.h>

/// A 'pure' closure; has no arguments, returns nothing.
typedef void (^VoidBlock)(void);

/// Returns: true if the block throws an `NSException`, otherwise false
BOOL throwsToBool(VoidBlock block);


//  ThrowsToBool.m
#import "ThrowsToBool.h"

BOOL throwsToBool(VoidBlock const block) {
    @try {
        block();
    }
    @catch (NSException * const notUsed) {
        return YES;
    }
    return NO;
}


// xxxTests-Bridging-Header.h
#import "ThrowsToBool.h"
Run Code Online (Sandbox Code Playgroud)

然后你可以写:

XCTAssert(throwsToBool {
   // test code that throws an NSException
})
Run Code Online (Sandbox Code Playgroud)

但它不适用于断言或前提条件:(

PS我的想法来自:http://modocache.io/xctest-the-good-parts