Question

Working my way through the Test-driven iOS Development book and found this test which I'm trying to get my head around:

#import "QuestionCreationTests.h" 
#import "StackOverflowManager.h"

@implementation QuestionCreationTests {
@private
    StackOverflowManager *mgr; 
}

- (void)setUp {
    mgr = [[StackOverflowManager alloc] init];
}

- (void)testNonConformingObjectCannotBeDelegate {
    STAssertThrows(mgr.delegate =
    (id <StackOverflowManagerDelegate>)[NSNull null], 
    @"NSNull should not be used as the delegate as doesn't" 
    @" conform to the delegate protocol");
}

This tests that a non-conforming object cannot be a delegate. My understanding is that it uses NSNull as a sample non-conforming object. It then casts this to an object of type id that conforms to the StackOverflowManagerDelegate protocol. It then checks if this is equal to mgr.delegate. Then if this raises an exception it fails the test. My question is: how does this raise an exception?

Can someone clarify?

If it helps, here's the preamble:

The application will ask the StackOverflowManager to provide its delegate with questions on a particular topic.That means that the StackOverflowManager class must have a delegate.

Fwiw, I'm aware that we'd now use XCTAssertThrows.

Was it helpful?

Solution

STAssertThrows throws an exception if the expression does not throw an exception.

The setDelegate method of StackOverflowManager is -

- (void)setDelegate:(id<StackOverflowManagerDelegate>)newDelegate {
    if (newDelegate && ![newDelegate conformsToProtocol: @protocol(StackOverflowManagerDelegate)]) {
        [[NSException exceptionWithName: NSInvalidArgumentException reason: @"Delegate object does not conform to the delegate protocol" userInfo: nil] raise];
    }
    delegate = newDelegate;
}

As NSNull does not conform to the StackOverflowManagerDelegate protocol, the setter will throw an exception. STAssertThrows will trap that exception and the test passes. If the setter did not throw an exception, then STAssertThrows will throw an exception and the test will fail

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top