OCHamcrest
OCHamcrest 是OC 的断言框架,提供更友好的断言接口。 OCHamcrest 的断言方法都是以assertThat 为前缀的。
一、Object
MOStudent *stu = [[MOStudent alloc] init];
stu.name = @"momo";
MOStudent *stu2 = nil;
assertThat(stu, conformsTo(@protocol(NSCoding)));
assertThat(stu, equalTo(stu));
assertThat(stu, hasDescription(startsWith(@"<MOStudent:")));
assertThat(stu, hasProperty(@"name", @"momo"));
assertThat(stu, instanceOf([NSObject class]));
assertThat(stu, isA([MOStudent class]));
assertThat(stu2, nilValue());
assertThat(stu, notNilValue());
assertThat(stu, sameInstance(stu));
二、Number
BOOL value1 = YES;
BOOL value2 = NO;
assertThatBool(value1, isTrue());
assertThatBool(value2, isFalse());
int num1 = 5;
float num2 = 2.5;
assertThatInt(num1, equalToInt(5));
assertThatFloat(num2, equalToFloat(2.5));
NSNumber *num3 = @(3.14);
assertThat(num3, closeTo(3.0f, 0.5));
assertThat(num3, lessThan(@(4)));
assertThat(num3, lessThanOrEqualTo(@(4)));
assertThat(num3, greaterThan(@(3)));
assertThat(num3, greaterThanOrEqualTo(@(3)));
三、String
NSString *str = @"Objective-C";
assertThat(str, equalTo(@"Objective-C"));
assertThat(str, containsSubstring(@"tive"));
assertThat(str, startsWith(@"Obj"));
assertThat(str, endsWith(@"-C"));
assertThat(str, equalToIgnoringCase(@"objective-c"));
四、Logical
NSString *str = @"Objective-C";
assertThat(str, allOf(startsWith(@"Objective"), endsWith(@"-C"), nil));
assertThat(str, anyOf(startsWith(@"Objective"), endsWith(@"-S"), nil));
assertThat(str, isNot(@"Swift"));
assertThat(str, isNot(endsWith(@"-S")));
五、Collection
NSArray *arr = [NSArray array];
assertThat(arr, isEmpty());
arr = @[@"a", @"b", @"c"];
assertThat(arr, contains(@"a", @"b", @"c", nil));
assertThat(arr, containsInAnyOrder(@"b", @"a", @"c", nil));
assertThat(arr, everyItem(instanceOf([NSString class])));
assertThat(arr, hasCount(greaterThan(@(2))));
assertThat(arr, hasCountOf(3));
assertThat(arr, hasItem(@"c"));
assertThat(@"c", isIn(arr));
assertThat(arr, hasItems(is(@"c"), equalToIgnoringCase(@"A"), @"b", nil));
assertThat(arr, hasItemsIn(@[is(@"c"), equalToIgnoringCase(@"A"), @"b"]));
assertThat(arr, onlyContains(startsWith(@"a"), nil));
assertThat(arr, onlyContains(instanceOf([NSString class]), nil));
assertThat(arr, onlyContainsIn(@[instanceOf([NSString class])]));
NSDictionary *dic = @{@"key1": @"value1", @"key2": @"value2"};
assertThat(dic, isNot(isEmpty()));
assertThat(dic, isNot(hasKey(@"key3")));
assertThat(dic, hasCountOf(2));
assertThat(dic, hasKey(@"key1"));
assertThat(dic, hasValue(@"value1"));
assertThat(dic, hasEntry(@"key1", @"value1"));
assertThat(dic, hasEntries(@"key1", @"value1", @"key2", @"value2", nil));
assertThat(dic, hasEntriesIn(@{@"key1": @"value1", @"key2": @"value2"}));
六、Decorator
int num1 = 5;
assertThatInt(num1, equalToInt(5));
assertThatInt(num1, is(equalToInt(5)));
NSString *cheese = @"cheese";
NSString *smelly = @"cheese";
assertThat(cheese, equalTo(smelly));
assertThat(cheese, is(equalTo(smelly)));
assertThat(cheese, is(smelly));
参考:Github、Document
|