在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相等技术?
发布于 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 :(
发布于 2015-04-07 04:39:55
在swift中没有等同于XCTAssertThrows的东西。现在,您不能使用本机函数,但是有一个解决方案可以通过一些objective-c帮助来解决。您可以使用Quick或仅使用Nimble。或者创建您自己的assert函数-请参阅本文- http://modocache.io/xctest-the-good-parts -潜在改进#2:将XCTAssertThrows添加到Swift
发布于 2015-10-16 20:06:44
https://stackoverflow.com/questions/24052739
复制相似问题