0

我正在编写带有期望的单元测试,我有一堆它们,它们的结构非常相似,所以我决定重构我的代码,但由于期望的满足而卡住了。也许你能给我一些想法?

带来2个测试示例:

- (void)test_init_withValidData_shouldGetID
{
    XCTestExpectation *expectation = [self expectationWithDescription:@"Waiting for request completion."];

    NSData *data = [[self readFromTxtFileNamed:@"data_4_20_example"] dataUsingEncoding:NSUTF8StringEncoding];
    
    [self.parser parseWithData: data completion:^(Model *model, Error error) {
        XCTAssertNotNil(model);
        
        Object *first = [model firstObject];
        XCTAssertNotNil(first);
        XCTAssertEqual(error, Error_None);
        
        NSString *ID = [firstAd ID];
        NSString *expectedID = @"4d7f-4440-bd29-2ec0e693fc80";
        XCTAssertEqualObjects(ID, expectedID);

        [expectation fulfill];
    }];

    [self waitForExpectationsWithTimeout:10.0 handler:^(NSError * _Nullable error) {
        NSLog(@"Error: %@", error.localizedDescription);
    }];
}

- (void)test_init_withValidData_shouldGetTitle
{
    XCTestExpectation *expectation = [self expectationWithDescription:@"Waiting for request completion."];

    NSData *data = [[self readFromTxtFileNamed:@"data_4_20_example"] dataUsingEncoding:NSUTF8StringEncoding];
    
    [self.parser parseWithData: data completion:^(Model *model, Error error) {
        XCTAssertNotNil(model);
        
        Object *first = [model firstObject];
        XCTAssertNotNil(first);
        XCTAssertEqual(error, Error_None);
        
        NSString *title = [first title];
        NSString *expectedTitle = @"My Title";
        XCTAssertEqualObjects(title, expectedTitle);

        [expectation fulfill];
    }];

    [self waitForExpectationsWithTimeout:10.0 handler:^(NSError * _Nullable error) {
        NSLog(@"Error: %@", error.localizedDescription);
    }];
}

如您所见,只有检查值不同,整个测试非常相似。我可以通过添加新方法以某种方式重构并缩短它们吗?

4

0 回答 0