1 单元测试

@implementation HPAlbumTest
- (void)testInitializer {
	HPAlbum *album = [[HPAlbum alloc] init];
	XCTAssert(album, @"Album alloc-init failed");
}

-(void)testPropertyGetters {
	HPAlbum *album = [[HPAlbum alloc] init];
	album.name = @"Album-1";
	NSDate *ctime = [NSDate date];
	album.creationTime = ctime;
	HPPhoto *coverPhoto = [[HPPhoto alloc] init];
	coverPhoto.album = album;
	album.coverPhoto = coverPhoto;
	NSArray *photos = @[coverPhoto];
	album.photos = photos;
	XCTAssertEqualObjects(@"Album-1", album.name);
	XCTAssertEqualObjects(ctime, album.creationTime);
	XCTAssertEqualObjects(coverPhoto, album.coverPhoto);
	XCTAssertEqualObjects(photos, album.photos);
}

2 代码覆盖率测试,

来检查测试的覆盖率。

3 异步测试

func test_async_fetchPlaces() {
	// 1. Create an expectation.
	let expectation: XCTestExpectation = expectationWithDescription("Async fetch")

	// 2. Provide sample test JSON.
	var sampleURL: NSURL? = NSBundle.testBundle().URLForResource("SampleResponse",withExtension: "json")

	XCTAssertNotNil(sampleURL, "Failed to get a valid URL to sample response file in Test Bundle.")

	placeManager.localResourceFileURL = sampleURL!

	// 3.
	placeManager.fetchPlacesWithCompletion({ (places: [Place]) in
		var optionalPlaces: [Place]? = places
		// 4.
		XCTAssertTrue(countElements(places) == 600, "Expected to get 600 results from the sample response.")

		// Fulfill the expectation
		expectation.fulfill()
	})

	// 5. The test will pause here, running the run loop, until the timeout is hit

	// or all expectations are fulfilled.
	waitForExpectationsWithTimeout(1.0, handler: { (error) in
		XCTAssertNil(error, "PlaceManager failed to process fetch from sample response in a reasonable time.");
	})
}

4 性能测试

func test_performance_processJSONRoot () {
	// Provide our sample test JSON.
	var sampleURL: NSURL? = NSBundle.testBundle().URLForResource("SampleResponse", withExtension: "json")

	XCTAssertNotNil(sampleURL, "Failed to get a valid URL to sample response file in Test Bundle.")

	let data = NSData(contentsOfURL: sampleURL)
	var root = NSJSONSerialization.JSONObjectWithData(data, options:.MutableContainers, error: nil) as NSMutableDictionary

	measureBlock({
		var placeObjects: [Place]? = self.placeManager.processJSONRoot(root)
		XCTAssert(placeObjects, "PlaceManager failed to process data.")
	})
}

5 依赖测试

当我们写单元测试的时候,不可避免的要去尽可能少的实例化一些具体的组件来保持测试既短又快。而且保持单元的隔离。在现代的面向对象系统中,测试的组件很可能会有几个依赖的对象。我们用mock来替代实例化具体的依赖class。mock是在测试中的一个伪造的有预定义行为的具体对象的替身对象。被测试的组件不知道其中的差异!你的组件是在一个更大的系统中被设计的,你可以很有信心的用mock来测试你的组件

OCMock

6 UI功能测试