我正在尝试编写 XCTest 并使用 Typhoon 注入(inject)模拟依赖项。
这是我的ViewController
中的代码:
- (instancetype)init {
self = [super init];
MDMainAssembly *assembly = (MDMainAssembly *) [TyphoonComponentFactory defaultFactory];
self.alertManager = [assembly alertManager];
return self;
}
以下是我尝试更改注入(inject)的方法:
self.mockedAlertManager = mock([MDAlertManager class]);
MDMainAssembly *assembly = [MDMainAssembly assembly];
TyphoonComponentFactory *factory = [TyphoonBlockComponentFactory factoryWithAssembly:assembly];
TyphoonPatcher *patcher = [[TyphoonPatcher alloc] init];
[patcher patchDefinition:[assembly alertManager] withObject:^id {
return self.mockedAlertManager;
}];
[factory attachPostProcessor:patcher];
但是测试失败,因为该工厂无法设置为默认值。我在 AppDelegate
工厂中配置:
TyphoonComponentFactory *factory = [[TyphoonBlockComponentFactory alloc] initWithAssemblies:@[
[MDMainAssembly assembly],
]];
[factory makeDefault];
如何摆脱这种情况?
最佳答案
我们为有限数量的情况创建了 defaultFactory 功能。主要是:
- 访问 Typhoon 并查找不受 Typhoon 管理的类的依赖项。一般来说,这不是必需的。
尽管您可以在测试中使用它,但我们建议您为每次测试运行创建和销毁一个 Typhoon 容器。为了避免重复,您可以创建一个方法,如下所示:
@implementation IntegrationTestUtils
+ (TyphoonComponentFactory*)testAssembly
{
TyphoonComponentFactory* factory = [[TyphoonBlockComponentFactory alloc] initWithAssemblies:@[
[MyAppAssembly assembly],
[MyAppKernel assembly],
[MyAppNetworkComponents assembly],
[MyAppPersistenceComponents assembly]
]];
id <TyphoonResource> configurationProperties = [TyphoonBundleResource withName:@"Configuration.properties"];
[factory attachPostProcessor:[TyphoonPropertyPlaceholderConfigurer configurerWithResource:configurationProperties]];
return factory;
}
。 。如果需要,您可以将修补程序附加到该程序集。
将修补程序附加到默认工厂:
如果您要将修补程序应用于默认程序集,您很可能想再次取消修补。此功能已积压 here 。
关于ios - 用 Typhoon 注入(inject)模拟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21906451/