mutableCopy
iOS で OCMock と GHUnitを使用するための呼び出しをモックしようとしています。
テストに合格したにもかかわらず、EXC_BAD_ACCESS
クリーンアップ中に例外が発生しました。その理由を突き止めようとしています。
これを見てください。このテストはmutableCopy
、 mockをモックできることを示していNSString
ます。このテストNSString
では、 ではなく、別の を返しNSMutableString
ます。これは、mutableCopy
期待が発せられ、テストが成功することを示すためのものです。
#import <GHUnitIOS/GHUnit.h>
#import "OCMock.h"
@interface TestItClass : GHTestCase @end
@implementation TestItClass
// Test that mutableCopy on an NSString is mockable.
- (void)test_1_mutableCopyOfString_shouldBeMockable_givenAStringIsReturned {
NSString *string = [OCMockObject mockForClass:NSString.class];
NSString *copy = @"foo";
[(NSString *) [[(id) string expect] andReturn:copy] mutableCopy];
// MutableCopy is mocked to return a string, not a mutable string!
// This is clearly wrong from a static typing point of view, but
// the test passes anyway, which is ok.
NSMutableString *result = [string mutableCopy];
GHAssertEquals(result, copy, nil);
[(id)string verify];
}
ここで、モックの期待値を変更してmutableCopy
、NSMutableString
. テストは引き続き成功しますが、テストを破棄するとEXC_BAD_ACCESS
例外が発生します。
- (void)test_2_mutableCopyOfString_shouldBeMockable_givenAMutableStringIsReturned {
NSString *string = [OCMockObject mockForClass:NSString.class];
NSMutableString *copy = [@"foo" mutableCopy];
[(NSString *) [[(id) string expect] andReturn:copy] mutableCopy];
// Now mutableCopy is mocked to return a mutable string!
// The test now blows up during the test teardown! Why?
NSMutableString *foo = [string mutableCopy];
GHAssertEquals(foo, copy, nil);
[(id)string verify];
}
@end
どちらのテストでも、検証はアサートに関して機能します。これは、両方のテストが適切に構築されており、モックの期待値が期待どおりに起動されていることを示しています。ただし、2 番目のテストは、メモリ アクセスが正しくないためティア ダウンに失敗します。
Simulator session started with process 7496
Debugger attached to process 7496
2013-03-11 18:23:05.519 UnitTests[7496:c07] TestItClass/test_2_mutableCopyOfString_shouldBeMockable_givenAMutableStringIsReturned ✘ 0.00s
2013-03-11 18:23:06.466 UnitTests[7496:c07] Re-running: TestItClass/test_2_mutableCopyOfString_shouldBeMockable_givenAMutableStringIsReturned <GHTest: 0x7793340>
Exception: EXC_BAD_ACCESS (code=1, address=0x11dfe3ea))
なぜそれが起こっているのか教えてください。
ありがとう、ジョー