我在一个应用程序上工作,列出了一项运动的当前现场比赛。使用 REST 从远程源获取有关实时游戏的信息。第一个请求给出了一个带有他们的 id 和相应的竞技场 id 的现场游戏列表。然后我必须从他们的 id 中获取竞技场名称。当一切都完成后,我发回一个包含现场游戏列表的 NSArray。
在测试通过块传递 NSArray 的解析方法时,我在 SenTestCase 中发现了一个奇怪的行为。在我的测试中,我可以做一个[myArray count]
并在 NSLog 中显示它的结果,但是当我STAssertEquals([myArray count], 1, @"Error description")
用 EXC_BAD_ACCESS 做一个测试崩溃时。
这是我的代码减少到最低限度,并且我删除了所有网络方面:
#import <SenTestingKit/SenTestingKit.h>
@interface LiveGameTests : SenTestCase
@end
@interface LiveGame : NSObject
@property (nonatomic) id gameID;
@property (strong, nonatomic) NSString *arenaName;
@end
@implementation LiveGame
// Create a live game object from a dictionary (this dictionary is the response of a first request to a remote server)
+(LiveGame *)gameWithData:(NSDictionary *)dict
{
LiveGame *liveGame = [[LiveGame alloc] init];
liveGame.gameID = dict[@"game_id"];
return liveGame;
}
// Complete a live game data with the element of a dictionary (those data are actualy fetched from a remote server in a different request.)
+(void)fetchRemainingData:(NSArray *)liveGameList completion:(void(^)(void))completion
{
LiveGame *liveGame = liveGameList[0];
liveGame.arenaName = @"arenaName";
completion();
}
// Parse a NSArray of NSDictionaries representing live game
+(void)parseArrayOfDictionary:(NSArray *)arrayToParse success:(void(^)(NSArray *liveGameList))success
{
NSMutableArray *liveGameList = [NSMutableArray arrayWithCapacity:[arrayToParse count]];
// Iterate on all the NSDictionary of the NSArray and create live game from each NSDictionary
[arrayToParse enumerateObjectsUsingBlock:^(NSDictionary *obj, NSUInteger idx, BOOL *stop)
{
liveGameList[idx] = [LiveGame gameWithData:obj];
}];
[LiveGame fetchRemainingData:liveGameList completion:^
{
success(liveGameList);
}];
}
@end
@implementation LiveGameTests
-(void)testParseArrayOfDictionary
{
[LiveGame parseArrayOfDictionary: @[@{@"game_id": @1}]
success:^(NSArray *liveGameList)
{
// This line work fine and print: 2013-03-08 13:39:35.288 ShotClock[55177:c07] liveGameList count = 1
NSLog(@"liveGameList count = %d",[liveGameList count]);
// This crash the test on a EXC_BAD_ACCESS. What's wrong?
STAssertEquals([liveGameList count], 1, @"The list of game must contain one unique live game but contain %@",[liveGameList count]);
}];
}
@end
NSLog(@"liveGameList count = %d",[liveGameList count]); =>这条线工作正常并打印:2013-03-08 13:39:35.288 ShotClock[55177:c07] liveGameList count = 1
STAssertEquals([liveGameList count], 1, @"游戏列表必须包含一个唯一的实时游戏,但包含 %@",[liveGameList count]); => 这会使 EXC_BAD_ACCESS 上的测试崩溃。怎么了?