如何通过 TyphoonPatcher 重置打过补丁的组件

How to reset patched components by TyphoonPatcher

我在集成测试中使用的 TyphoonPatcher 有问题。我正在使用 KIF 进行集成测试。有时我需要存根 http 客户端或 class 负责在数据库中保存数据。最简单的方法是使用 TyphoonPatcher。

假设我需要补丁 patch knight to stubbed knight for TestCase A, for all test cases,所以我在beforeAll回调中这样做

负责修补组件的代码:

MiddleAgesAssembly* assembly = [[MiddleAgesAssembly assembly] activate];

TyphoonPatcher* patcher = [[TyphoonPatcher alloc] init];
[patcher patchDefinitionWithSelector:@selector(knight) withObject:^id{
Knight* mockKnight = mock([Knight class]);
[given([mockKnight favoriteDamsels]) willReturn:@[
    @"Mary",
    @"Janezzz"
]];

return mockKnight;

}];

[assembly attachPostProcessor:patcher];

Knight* knight = [(MiddleAgesAssembly*) factory knight]

现在在 TestCase B 中,我想要应用程序的清晰状态,没有任何修补的组件。

有问题吗? class B 中的骑士仍被替换为其他嘲笑或存根 class。

有什么方法可以从 TestCase A 恢复补丁吗?

TyphoonPatcher 是一种 TyphoonAbstractDetachableComponentFactoryPostProcessor 所以你可以简单地调用补丁程序的 detach 方法。请注意,这仅在补丁程序是最后一个要连接的 post 处理器时才有效。台风不知道如何将状态展开到任意深度。

**示例:**

- (void)test_allows_detaching_patcher
{
    [self applyAPatch];
    [self assertPatchApplied];

    XCTAssertFalse([_assembly componentForKey:@"knight"] == [_assembly componentForKey:@"knight"]);
    XCTAssertTrue([_assembly componentForKey:@"cavalryMan"] == [_assembly componentForKey:@"cavalryMan"]);

    [_patcher detach];

    Knight *knight = [_assembly componentForKey:@"knight"];
    LogDebug(@"%@", [knight favoriteDamsels]);
}

一般使用单独的Typhoon进行测试:

另请注意,在 general 中,我们建议您使用单独的 Typhoon 实例进行测试。这样做时,应该不需要分离修补程序。但是,如果它更适合您的特定情况,那么分离是可行的方法。

通常会为一个测试用例修补组件,如果您想摆脱已修补的组件,并为下一个 KIFTestCase 测试准备好状态,您只需输入:

exit(0)

afterAll,喜欢:

- (void)afterAll {
    [super afterAll];
    exit(0);
}

请注意,这仅适用于 运行 TestCase,如果您想回滚 TestCase 中某些测试方法的修补组件,您应该使用上述解决方案。