xcode的测试覆盖率报告可以让我们直观地看到哪些target,哪些类,哪些方法,方法的哪些路径被测试到了,还是对测试很有帮助的。每次执行测试后,这个数据就会产生,通过导航到”Show the report navigator”,点击被测target的Test记录,右边选择Coverage标签页查看。
要允许这个数据产生,只要分别针对被测target和测试target都勾选上Test页面里面的Gather coverage data选项即可,注意,两个target都要勾选才行。
展开每个被统计的类,可以查看哪些公共的方法被测试了哪些没有,覆盖率应该是统计了 被测试的代码路径/总共代码路径而不仅仅是被测试的公共方法/总共的公共方法
如果发现那个类的覆盖率不是100%,我们可以双击那个类,进入代码编辑界面,要查看哪个方法是否被测试覆盖,我们可以通过移动鼠标到那个方法的代码所在地方的最右边那个边栏,悬停鼠标,通过红绿色块的指示来看出我们当前的测试代码到底覆盖了哪里还有哪里没有覆盖。绿色代表覆盖到了,红色代表没有覆盖。
这是被测试类的代码:
#import "MyComponent.h"
@implementation MyComponent
- (NSInteger)sayHello{
NSLog(@"Hello....");
return 1;
}
- (NSInteger)sayGoodbye{
NSLog(@"Goodbye...");
return 0;
}
/**
type:1,2,3,other
@param type <#type description#>
*/
- (NSInteger)sayWordsWithType:(NSInteger)type{
switch (type) {
case 1:
NSLog(@"Good day!");
return 1;
case 2:
NSLog(@"Good morning!");
return 2;
case 3:
NSLog(@"Good afternoon!");
return 3;
default:
NSLog(@"Wrong option!");
return 0;
}
}
@end
这是被测试类的单元测试代码:
#import <XCTest/XCTest.h>
#import "MyComponent.h"
@interface MyComponentTests : XCTestCase
@property (nonatomic, strong) MyComponent *component;
@end
@implementation MyComponentTests
- (void)setUp {
[super setUp];
self.component = [[MyComponent alloc] init];
}
- (void)tearDown {
self.component = nil;
[super tearDown];
}
- (void)testSayHelloShouldReturn1{
NSInteger result = [self.component sayHello];
XCTAssertEqual(result, 1, @"sayHello方法应该返回1");
}
- (void)testSayGoodbyeShouldReturn0{
NSInteger result = [self.component sayGoodbye];
XCTAssertEqual(result, 0, @"sayGoodbye方法应该返回0");
}
- (void)testSayWordsWithType1ShouldReturn1{
NSInteger result = [self.component sayWordsWithType:1];
XCTAssertEqual(result, 1, @"testSayWordsWithType方法应该返回1");
}
//- (void)testSayWordsWithType1ShouldReturn2{
// NSInteger result = [self.component sayWordsWithType:2];
// XCTAssertEqual(result, 2, @"testSayWordsWithType方法应该返回2");
//}
//
//- (void)testSayWordsWithType1ShouldReturn3{
// NSInteger result = [self.component sayWordsWithType:3];
// XCTAssertEqual(result, 3, @"testSayWordsWithType方法应该返回3");
//}
//- (void)testSayWordsWithType1ShouldReturn0{
// NSInteger result = [self.component sayWordsWithType:5];
// XCTAssertEqual(result, 0, @"testSayWordsWithType方法应该返回0");
//}
@end
这是被测试类的测试覆盖情况。这两个方法的代码路径都被测试到了,所以全部是绿色的。
这个方法的代码路径只有一部分被测试到,所以一部分是绿色的,另外的一部分是绿色的。
如果我们把上面测试代码的注释部分解注,那么这个只有部分被覆盖的方法就会变成全部被测试覆盖,就是全绿了。
然后,整个类的代码测试覆盖率终于也达到了100%。
本文介绍了如何在Xcode中查看和提高单元测试覆盖率。通过启用'Gather coverage data'选项,可以在测试报告中看到目标、类和方法的覆盖率。未被测试覆盖的代码会显示为红色,而已覆盖的代码则显示为绿色。通过这种方式,可以针对性地改进测试,确保代码全面受测,从而达到100%的覆盖率。
988

被折叠的 条评论
为什么被折叠?



