单测框架Kiwi的使用
该文章事例demo地址:UnitTestDemo
如果需要持续集成单元测试可参照:Jenkins+fastlane做单元测试
1.简介
Kiwi是一个iOS平台的BDD的测试框架,它提供断言、stub和mock等功能,方便开发写出可读性好的单元测试。
2.集成
- cocoapod集成
target 'YourTests' do
pod 'Kiwi', '~> 3.0.0'
end
- Xcode集成Template
clone Kiwi代码到本地,进入Xcode Templates目录,执行./install-templates.sh
-
创建Kiwi单测类
通过Kiwi Spec模版创建
3.语法
1.简单的示例
describe(@"Team", ^{
context(@"when newly created", ^{
it(@"should have a name", ^{
id team = [Team team];
[[team.name should] equal:@"Black Hawks"];
});
it(@"should have 11 players", ^{
id team = [Team team];
[[[team should] have:11] players];
});
});
});
- describe - 描述我们需要测试的对象内容;
- context - 描述测试上下文;
- it - 是测试的本体,描述该单测需要满足的条件
其他行为描述的关键字
- beforeAll(aBlock) - 当前scope内部的所有的其他block运行之前调用一次并且只调用一次,一般在这里做一些全局的初始化工作
- afterAll(aBlock) - 当前scope内部的所有的其他block运行之后调用一次,一般在这里做一些全局的清理工作
- beforeEach(aBlock) - 在scope内的每个it之前调用一次,对于context的配置代码应该写在这里
- afterEach(aBlock) - 在scope内的每个it之后调用一次,用于清理测试后的代码
- specify(aBlock) - 可以在里面直接书写不需要描述的测试
- pending_(aString, aBlock) - 只打印一条log信息,不做测试。这个语句会给出一条警告,可以作为一开始集中书写行为描述时还未实现的测试的提示。
2.Expectations
- 同步断言
should
shouldNot
shouldBeNil
shouldNotBeNil
context(@"convertToFormatedStringFromPayAmount", ^{
it(@"payAmount is 2.00,then formatedAmountString should be 2", ^{
payAmount = [NSDecimalNumber decimalNumberWithString:@"2.00"];
formatedAmountString = [OrderUtility convertToFormatedStringFromPayAmount:payAmount];
[[formatedAmountString should] equal:@"2"]; //formatedAmountString应该等于“2”
});
});
- 异步断言:用于需要测试的结果是异步返回的情况
shouldEventually
shouldNotEventually
shouldEventuallyBeforeTimingOutAfter(timeout)
shouldNotEventuallyBeforeTimingOutAfter(timeout)
shouldAfterWait
shouldNotAfterWait
shouldAfterWaitOf(timeout)
shouldNotAfterWaitOf(timeout)
expectFutureValue(futureValue)
context(@"fetchConfigInfoCompletedBlock", ^{
it(@"configs should not be nil", ^{
__block NSDictionary *tmpConfigs;
[OrderUtility fetchConfigInfoCompletedBlock:^(NSDictionary * _Nonnull configs) {
tmpConfigs = configs; //异步回调回来数据
}];
// [[expectFutureValue(tmpConfigs) shouldNotAfterWaitOf(5)] beNil];
[[expectFutureValue(tmpConfigs) shouldEventuallyBeforeTimingOutAfter(5)] beNil]; //5s之后检查断言,正常就测试通过,否则异常
});
});
- 消息模式
KWReceiveMatcher:一般用来判断对象是否能响应某些消息
[[mockNavController should] receive:@selector(pushViewController:animated:)];
-
期望是数字的比较
[[subject shouldNot] beNil]
[[subject should] beNil]
[[subject should] beIdenticalTo:(id)anObject] - compares id's
[[subject should] equal:(id)anObject]
[[subject should] equal:(double)aValue withDelta:(double)aDelta]
[[subject should] beWithin:(id)aDistance of:(id)aValue]
[[subject should] beLessThan:(id)aValue]
[[subject should] beLessThanOrEqualTo:(id)aValue]
[[subject should] beGreaterThan:(id)aValue]
[[subject should] beGreaterThanOrEqualTo:(id)aValue]
[[subject should] beBetween:(id)aLowerEndpoint and:(id)anUpperEndpoint]
[[subject should] beInTheIntervalFrom:(id)aLowerEndpoint to:(id)anUpperEndpoint]
[[subject should] beTrue]
[[subject should] beFalse]
[[subject should] beYes]
[[subject should] beNo]
[[subject should] beZero] 期望是字符串的比较(支持正则比较)
[[subject should] containString:(NSString*)substring]
[[subject should] containString:(NSString*)substring options:(NSStringCompareOptions)options]
[[subject should] startWithString:(NSString*)prefix]
[[subject should] endWithString:(NSString*)suffix]
[[subject should] matchPattern:(NSString*)pattern]
[[subject should] matchPattern:(NSString*)pattern options:(NSRegularExpressionOptions)options]
3.stub
- 有一些测试场景,需要依赖其他业务的返回,或者是接口返回数据;往往在测试的时候,我们需要假设这些外在的条件是确定的,然后来验证我们的功能;这个时候就可以通过stub来将外在的条件的返回为需要的值;
- 需要注意的是Kiwi的stub只生效一次,在一个it执行之后就会被清空,如果需要在每个it中都生效,可以将stub写在beforeEach块中,这样在每个it执行之前都会执行一次stub
示例
需要测试的方法依赖其他业务的返回,测试的关注点是自己的业务是否正常,这时候需要将外在的依赖变化设置为已知的
+ (NSDecimalNumber *)calculatePayAmountWithPrice:(NSDecimalNumber *)price {
if (price == nil || [price doubleValue] == 0) {
return nil;
}
NSDecimalNumber *couponNumber = [CouponUtility fetchAvaiableCoupon]; // fetchAvaiableCoupon函数的返回是其他业务模块提供
NSDecimalNumber *payAmount = price;
if ([couponNumber doubleValue]) {
payAmount = [price decimalNumberBySubtracting:couponNumber];
}
return payAmount;
}
context(@"calculatePayAmountWithPrice", ^{
it(@"price is 25 and coupon is 5,then repayAmount should be 20", ^{
[CouponUtility stub:@selector(fetchAvaiableCoupon) andReturn:[NSDecimalNumber decimalNumberWithString:@"5.00"]]; //stub其他模块的变因为已知的
price = [NSDecimalNumber decimalNumberWithString:@"25.00"];
NSDecimalNumber *repayAmount = [OrderUtility calculatePayAmountWithPrice:price];
[[repayAmount should] equal:[NSDecimalNumber decimalNumberWithString:@"20.00"]];
});
});
4.mock
- 模仿类的对象,使我们能够在完整的实现存在之前关注对象之间的交互行为,并将对象从依赖项中分离出来,这些依赖项在运行时可能过于复杂和不可控;
- 通常mock会配合stub一起使用,来模拟一个对象的某些行为
示例
我们需要测试UI界面的按钮点击是否正常跳转到预期的界面,如果不mock的话,我们需要去模拟出这个场景出来,往往这个是比较困难的;使用mock就能让我们跳出这个场景的再现,把重心放在我们需要验证的地方
// UI测试
context(@"Test Push", ^{
it(@"should push to TestVC", ^{
ViewController *vc = [[ViewController alloc] init];
UINavigationController *mockNavController = [UINavigationController mock];
[vc stub:@selector(navigationController) andReturn:mockNavController]; //将vc的导航控制器指定为mock出的对象
[[mockNavController should] receive:@selector(pushViewController:animated:)];
KWCaptureSpy *spy = [mockNavController captureArgument:@selector(pushViewController:animated:) atIndex:0];
[vc testPush:nil];
id obj = spy.argument;
TestViewController *testVC = obj;
[[testVC should] beKindOfClass:[TestViewController class]];
});
});
5.截获参数
KWCaptureSpy:一般用于函数调用时参数的截获;例如:
KWCaptureSpy *spy = [mockNavController captureArgument:@selector(pushViewController:animated:) atIndex:0];
[vc testPush:nil];
id obj = spy.argument;
6.异步测试
通常使用Kiwi提供的异步期望判断方法,设置超时时间,取超时时间之后单测的结果
示例
context(@"fetchConfigInfoCompletedBlock", ^{
it(@"configs should not be nil", ^{
__block NSDictionary *tmpConfigs;
[OrderUtility fetchConfigInfoCompletedBlock:^(NSDictionary * _Nonnull configs) {
tmpConfigs = configs;
}];
[[expectFutureValue(tmpConfigs) shouldEventuallyBeforeTimingOutAfter(5)] beNil];
});
// 未实现的测试用例,会输出一条log
pending_(@"configs dueDate should not be nil", ^{
});
});
4.参考资料
- Wiki
- Kiwi单测博客