Should I still bother with releasing objects in a unit test?
I noticed in Apple's "iPhoneUnitTests" sample project objects a开发者_Python百科re [[object alloc] init] in the setup method but never released anywhere in the unit test?
Thanks!
I would still do proper memory management.
I feel too dirty typing init
or retain
without typing release
. It's a good habit to have.
Also, as Epsilon Prime mentioned in the comments, being able to test for leaks is useful.
Its a good idea to always practice good memory management. It obviously can't hurt you, even if it doesn't potentially help. In addition, more practice with proper memory management (instead of saying "its not so important here") can only make you less likely to make mistakes down the road when it is important.
Don't abandon best practices just because you see such-and-such sample code that doesn't follow them. My guess is that such sample code probably isn't written by those with a lot of experience (because those people are doing more important jobs), so while the sample code may demonstrate what it's intended to show it usually isn't the best thing to examine for issues that are orthogonal to the sample's intended purpose (such a best coding practices).
Both test suites do practice proper memory management.
CalcTest is merely assigning variables to objects that exist as part of the AppDelegate, i.e. it never retains them so it never 'owns' them.
CalculatorTest releases the objects it owns in tearDown, as it is supposed to per the unit testing documentation.
I'd say it's still important, yes, but not as critical as finding leaks in your actual code. Leaky unit tests can chew up more memory, especially if you choose not to release anything. Also, if you run your unit tests in Instruments to look for leaks (I sometimes do this, since I'm testing a framework rather than a normal app) leaky unit tests can distract from the actual leaks you're trying to find.
Sample code may be quick-n-dirty, but that's never good rationale for poor memory management. Best practice for unit tests is to always release in tearDown
what you allocate in setUp
, and take care of memory allocated in a method before exiting that method. I tend to autorelease more in unit tests than in normal code, since it's often simpler. Because each test method is run in a separate instance of the enclosing test class, the setup/teardown overhead will dominate any penalty from autorelease pools.
精彩评论