jeudi 21 mai 2015

How to write a unit test in iOS for an expected assert/assertionFailure?

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?

Aucun commentaire:

Enregistrer un commentaire