It looks like this functionality should be supported in the upcoming Swift 2.0/XCode 7 versions, which apparently will include try/catch goodness, so this question will likely be moot. I'll try to update this post accordingly when they are out of beta.
In Swift, though I assume the question/answer would be applicable to Objective-C, I want to write a function foo
of the format:
public class SomeClass{
public func foo(someString:String){
//validate someString
assert(!someString.isEmpty, "The someString parameter cannot be empty.")
}
}
I use an assert
call because I believe this is what is recommended by Apple as opposed to throwing exceptions, as is common in other languages.
However, in my unit test, I want to be able to ensure that the function indeed fails when the someString
parameter is an empty String:
class SomeClass_Tests:XCTestCase{
func test_foo_someStringParamaterIsEmpty_error(){
//ACTION
let someClassInstance = SomeClass()
someClassInstance.foo("")
//VALIDATE
//**What goes here?
}
}
I can find no documentation or posts regarding this situation, even though I believe this is a highly important unit test to ensure proper behavior and usage of classes and libraries.
In other languages that include exceptions/exception handling, the assert
would be replaced with something like throw SomeError()
and then, in the unit test you could simply wrap the action in a try
/catch
block and assert that the exception was indeed set, like this:
class SomeClass_Tests:XCTestCase{
func test_foo_someStringParamaterIsEmpty_error(){
//ACTION
let someClassInstance = SomeClass()
var expectedException:SomeException? = nil
try{
someClassInstance.foo("")
}catch(someException:SomeException){
expectedException = someException
}
//VALIDATE
XCTAssertIsNotNil(expectedException)
}
}
But there are no such constructs or equivalent work-arounds in Swift that I've seen in the documentation. Are there any known solutions or workarounds for performing tests like this?
Matt Gallagher's CwlPreconditionTesting project on github adds a catchBadInstruction
function which gives you the ability to test for assertion/precondition failures in unit test code.
The CwlCatchBadInstructionTests file shows a simple illustration of its use. (Note that it only works in the simulator for iOS.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With