Note that there are some explanatory texts on larger screens.

plurals
  1. POHow can I unit-test init methods in Objective-C?
    primarykey
    data
    text
    <p>I'm unit testing a Mac App in Xcode 5 using the new XCTest framework. Specifically, I'm trying to test that a class implements an (as yet unwritten!) <code>- (id)initWithStream:(NSInputStream)stream</code> method. So I have the start of my test:</p> <pre><code>- (void)testInitWithStream { // Should have an init method named initWithStream: XCTAssertTrue([[MYParser alloc] respondsToSelector:@selector(initWithStream:)], @"'initWithStream:' not implemented."); </code></pre> <p>Which works fine; the test currently fails as expected. It's the next part, which attempts to run the as-yet-unwritten method, that's causing me grief:</p> <pre><code> // Should return nil if no valid stream is passed XCTAssertNil([[MYParser alloc] performSelector:@selector(initWithStream:) withObject:nil], @"should get nil on 'initWithStream:' with no stream."); </code></pre> <p>Xcode gives me the error "PerformSelector names a selector which retains the object." I'm using <code>performSelector:withObject:</code> because attempting to call the selector directly results in an error that "No visible @interface for 'MYParser' declares the selector 'initWithStream:'."</p> <p>My test suite has <code>GCC_WARN_UNDECLARED_SELECTOR</code> turned off, but these are errors, not warnings. How can I test the init methods of objects when the test needs to cover the situation where the method may not be implemented (even as a definition) yet?</p> <p>The method may not be implemented yet because I'm writing my tests first; is this right, or should I be writing my class definitions first, then my tests, then the actual implementation? (I'm looking for consensus and best-practice on this point, not just opinion.)</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload