0

I'm new with Unit Test and I've got question about it.

In my source code I have subclassed NSMutableArray. NSMutableArray must have implemented primitive NSMutableArray and NSArray methods. These methods in some case throws NSExceptions like NSRangeExceptions.

The question is: "When I make unit tests for this primitive methods should I write case for NSExceptions?

Example:

//array with 3 objects
STAssertThrows([array insertObject:object atIndex:8], @"");
  1. Is this correct?
  2. Is this neccesary?
Peter Hosey
  • 95,783
  • 15
  • 211
  • 370
Tomasz Szulc
  • 4,217
  • 4
  • 43
  • 79

1 Answers1

1

There are two cases to consider: Asserting that an exception will be thrown, and asserting that an exception will not be thrown.

The latter is not necessary, but can still be a good idea. It's an opportunity to provide a more explicit description in the assertion message of what you were expecting to happen, or not to happen. But, you can skip STAssertNoThrow and the exception will still fail the test.

If you want the exception to happen, then you will need to assert that, like you did in the code in the question. You should provide a meaningful assertion message, though, rather than the empty string.

Peter Hosey
  • 95,783
  • 15
  • 211
  • 370
  • Thank you. I don't want this exception (`NSExceptionRange`) in my code. This is programmer error, so, when it's happend, then app will crash. So this is normal behaviour of `insertObject` method. When index is out of range, then crash. So the questions are: (1)Is this case in Unit Tests neccesary? (2) Should I use STAssertThrows only when I have to catch exceptions and then do something with it? – Tomasz Szulc Feb 21 '13 at 21:11
  • 1
    @TomaszSzulc: (1) Yes, it's worth testing that your methods handle nonsense, such as out-of-range inputs, as well as they handle valid inputs. (2) You should use `STAssertThrows` when a particular exception is the correct result of an expression. That function will catch the exception and fail the test for you; you don't need to do anything beyond that. – Peter Hosey Feb 21 '13 at 22:07