gpt4 book ai didi

ios - 使用 OCMock 意外崩溃,在 NSString 上模拟 'mutableCopy'

转载 作者:行者123 更新时间:2023-11-29 11:02:15 25 4
gpt4 key购买 nike

我正在尝试在 iOS 上使用 OCMock 和 GHUnit 模拟对 mutableCopy 的调用。

尽管测试通过了,但我在清理过程中遇到了 EXC_BAD_ACCESS 异常,我正在尝试找出原因。

看看这个。此测试表明可以在模拟 NSString 上模拟 mutableCopy。在此测试中,我返回了另一个 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

在这两个测试中,验证工作,至于断言。这表明这两个测试都构建良好,并且模拟期望按预期被触发。然而,第二个测试在拆卸时因内存访问错误而失败:

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))

你能告诉我为什么会发生这种情况吗?

谢谢,乔

最佳答案

您面临的问题是由 ARC 遵循 Basic Memory Management Rules 的事实引起的.具体来说:

  • You own any object you create

    You create an object using a method whose name begins with “alloc”, “new”, “copy”, or “mutableCopy” (for example, alloc, newObject, or mutableCopy).

因此解决方案是查看调用选择器以确定是否保留 returnValue

希望对您有所帮助。

关于ios - 使用 OCMock 意外崩溃,在 NSString 上模拟 'mutableCopy',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15345899/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com