我正在开发一个列出当前体育赛事的应用程序。有关实时游戏的信息是使用REST从远程源获取的。第一个请求给出了他们的id和相应的竞技场ID的实时游戏列表。然后我必须从他们的id中获取竞技场名称。当一切都完成后,我发回一个包含实时游戏列表的NSArray。
我在测试通过块传递NSArray的解析方法时,在SenTestCase中发现了一个奇怪的混淆。在我的测试中,我能够执行[myArray count]
并在NSLog中显示结果,但是当我使用EXC_BAD_ACCESS执行STAssertEquals([myArray count], 1, @"Error description")
测试时崩溃。
这是我的代码减少到最小,我删除所有网络方面:
#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]); =&GT;此行工作正常并打印:2013-03-08 13:39:35.288 ShotClock [55177:c07] liveGameList count = 1
STAssertEquals([liveGameList count],1,@“游戏列表必须包含一个唯一的实时游戏,但包含%@”,[liveGameList count]); =&GT;这使EXC_BAD_ACCESS上的测试崩溃。怎么了?
答案 0 :(得分:1)
您的应用程序崩溃了,因为
STAssertEquals([liveGameList count], 1, @"The list of game must contain one unique live game but contain %@",[liveGameList count])
尝试将%@ formatter应用于[liveGameList count]的结果。但是%@期望一个Objective C对象,其中[liveGameList count]返回标量“1”。运行时将该标量转换为指向0x00000001的指针,并尝试使用它在那里找到的“对象”。但这不是一个有效的指针,因此运行时会引发无效的地址异常。
答案 1 :(得分:0)
我认为STAssertEquals需要2个对象,你应该做类似
的事情STAssertTrue([myArray count] == expectedCount, @"Count is wrong);