首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >使用XCTAssertThrows模拟进行Swift单元测试

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

Stack Overflow用户
提问于 2014-06-05 14:05:50
回答 4查看 3.8K关注 0票数 18

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

并进行测试以检查它的工作情况。在objective C中,我可以像这样编写测试方法:

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

什么是Swift相等技术?

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2015-08-13 08:19:13

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

//  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
})

但它不适用于assert或precondition :(

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

票数 2
EN

Stack Overflow用户

发布于 2015-04-07 04:39:55

在swift中没有等同于XCTAssertThrows的东西。现在,您不能使用本机函数,但是有一个解决方案可以通过一些objective-c帮助来解决。您可以使用Quick或仅使用Nimble。或者创建您自己的assert函数-请参阅本文- http://modocache.io/xctest-the-good-parts -潜在改进#2:将XCTAssertThrows添加到Swift

票数 1
EN

Stack Overflow用户

发布于 2015-10-16 20:06:44

我认为最好的方法是添加一座桥。

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

这对我很管用。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/24052739

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档