Hard to test things


So I’d been thinking. Because I’m back into iPhone development and getting warmed up not only to ObjC issues and errors but also C++ oddities, I’m wondering how do you write tests for some of the more difficult things to capture? For instance, I’ve figured out how to capture some of the manual reference counting that’s required by CocoaTouch. (I assert that objects passed into other objects are properly retained and properly released when the object itself is released.) Still I can’t capture the more involved memory management problems. How do you assert an autorelease? What about dynamic memory allocation with pointers? I ended up with a single method that dynamically allocates for a pointer via malloc. I then changed it to use new with array notation.

void MySpecialObject::writeRequestToStream(CFStringRef aRequest, CFWriteStreamRef requestStream)
{
if(CFWriteStreamGetStatus(requestStream) == kCFStreamStatusNotOpen) CFWriteStreamOpen(requestStream);
UInt8* convertedString =(UInt8*)convertToCString(aRequest);
CFWriteStreamWrite(requestStream, convertedString, CFStringGetLength(aRequest));
free(convertedString);
}

It’s used in one spot so far and I’ve manually added the free without a prior failing test. I felt dirty. Assuming there were no call to free, how would you write a failing test for the code above? Is this just one of those things where you have to be extra careful? Maybe I should investigate the use of Velocity style code macros/templates that expand after keying special abbreviation similar to what we have in IntelliJ. I can imagine something like “cstr” expanding to:

char *myCStr = new char[size];
// use myCStr here
free(myCStr);

With the ability to tab through highlighting the variable name, declared size and commented insert code section. Any bright ideas?

3 thoughts on “Hard to test things

  1. char *myCStr = new char[size];
    // use myCStr here
    free(myCStr);

    should read

    char * myCStr = new char[size];
    //
    delete [] myCstr;

    remember, new/delete new[]/delete[] malloc()/free()

  2. oh yeah — and for testing pools – I wonder if you can uses some of the magic of NSDebug.h

    and/or possibly overriding – autorelease on your object – or is that a bad thing?

  3. I’m showing my C/C++ ignorance here. I didn’t realize you had to match up memory release schemes. My bigger question remains, how would I write a failing test? Also, I thought autorelease was specific to ObjC.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s