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

时间:2014-06-05 06:05:50

标签: 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等技术?

5 个答案:

答案 0 :(得分:2)

我认为assert() - 函数应仅用于调试目的。不仅仅是因为Apple的Swift-Book(https://itun.es/de/jEUH0.l)发表了以下声明:

“断言会导致您的应用终止,并且无法替代设计您的代码,从而无法出现无效条件。”

这就是为什么我会按如下方式解决这个问题:

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()

答案 1 :(得分: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"

然后你可以写:

XCTAssert(throwsToBool {
   // test code that throws an NSException
})

但它不适用于断言或先决条件:(

PS我从http://modocache.io/xctest-the-good-parts

得到了这个想法

答案 2 :(得分:0)

在swift中没有与XCTAssertThrows等效的东西。目前你不能使用本机功能,但有一个解决方案,有一些Objective-c帮助。您可以使用Quick,也可以只使用Nimble。或者创建自己的断言函数 - 请参阅此文章 - http://modocache.io/xctest-the-good-parts - 潜在改进#2:将XCTAssertThrows添加到Swift

答案 3 :(得分:0)

最好的方法是加入我认为的桥梁。

请查看https://gist.github.com/akolov/8894408226dab48d3021

它对我有用。

答案 4 :(得分:0)

Swift 2中的正确方法:

class Square : NSObject{

    let sideLength: Int

    init(sideLength: Int) throws { // throwable initializer
        guard sideLength >= 0 else { // use guard statement
           throw ...// your custom error type
        }

        self.sideLength = sideLength
        super.init()
    }
}

并测试:

func testInitThrows() {
        do {
            _ = try Square(sideLength: -1) // or without parameter name depending on Swift version
            XCTFail()
        } catch ... { // your custom error type

        } catch {
            XCTFail()
        }
    }