如何使用ocUnit编写地理位置的单元测试

时间:2011-02-03 00:21:27

标签: objective-c nsstring ocunit

我目前正在使用一个简单的对象,它将lat和lng值保存为NSString。但是,当我试图断言它们是平等的时,我会用这种方法失败

- (void) testLocationParseJson {
  NSArray* items = //some array the represents the json returned from google ...
  LocationParseJson* sut = [[LocationParseJson alloc] init];
  Location* actualLocation = [sut parseJson:items];

  NSString* actualLatitude = actualLocation.lat;
  NSString* actualLongitude = actualLocation.lng;

  STAssertEqualObjects(expectedLocation.lat, actualLocation.lat, @"The actual location latitude was %@", actualLocation.lat);
}

这是显示的错误

错误: - [LocationParseJsonTest testLocationParseJson]:'41 .6756668'应该等于'41 .6756668'实际位置纬度为41.6756668

所以我尝试使用“isEqual”

进行AssertTrue方法
STAssertTrue([expectedLocation.lat isEqual: actualLocation.lat], @"The actual location latitude was %@", actualLocation.lat);

我得到同样的错误

错误: - [LocationParseJsonTest testLocationParseJson]:“[expectedLocation.lat isEqual:actualLocation.lat]”应为true。实际位置纬度为41.6756668

我应该如何比较ocUnit中的这些NSString值?这是位置fyi的.h文件

@interface Location : NSObject {
  NSString* lng;
  NSString* lat;
}

@property (nonatomic, retain) NSString* lng;
@property (nonatomic, retain) NSString* lat;

@end

2 个答案:

答案 0 :(得分:2)

这个ocUnit问题的最终解决方案是创建一个NSDecimalNumber并使用STAssertTrue与isEqual进行比较。希望这有助于其他人!

- (void) testLocationParseJson {
  NSString* data = @"{\"name\":\"50035\",\"Status\":{\"code\":200,\"request\":\"geocode\"},\"Placemark\":[{\"id\":\"p1\",\"address\":\"Bondurant, IA 50035, USA\",\"AddressDetails\":{\"Accuracy\":5,\"Country\":{\"AdministrativeArea\":{\"AdministrativeAreaName\":\"IA\",\"Locality\":{\"LocalityName\":\"Bondurant\",\"PostalCode\":{\"PostalCodeNumber\":\"50035\"}}},\"CountryName\":\"USA\",\"CountryNameCode\":\"US\"}},\"ExtendedData\": {\"LatLonBox\": {\"north\": 41.7947250,\"south\": 41.6631189,\"east\": -93.3662679,\"west\": -93.5322489}},\"Point\":{\"coordinates\":[-93.4805335,41.6756668,0]}}]}";
  NSArray* items = [data JSONValue];

  NSDecimalNumber* expectedLat = [NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:@"%@", @"41.6756668"]];
  NSDecimalNumber* expectedLng = [NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:@"%@", @"-93.4805335"]];

  LocationParseJson* sut = [[LocationParseJson alloc] init];
  Location* actualLocation = [sut parseJson:items];

  STAssertTrue([expectedLat isEqual: actualLocation.lat], @"The actual location lat was %@", actualLocation.lat);
  STAssertTrue([expectedLng isEqual: actualLocation.lng], @"The actual location lng was %@", actualLocation.lng);
}

答案 1 :(得分:1)

我相信在比较NSStrings时你应该使用isEqualToString方法来比较它们。

尝试:
STAssertTrue([expectedLocation.lat isEqualToString:actualLocation.lat], @"The actual location latitude was %@", actualLocation.lat);

编辑:this StackOverflow question中的第一个答案有一些可能的解释,说明为什么你的方式不起作用。