Injecting mock with Typhoon

泪湿孤枕 提交于 2019-12-10 22:19:40

问题


I'm trying to write XCTest and inject mocked dependency with Typhoon.

Here is code in my ViewController:

   - (instancetype)init {
    self = [super init];

    MDMainAssembly *assembly = (MDMainAssembly *) [TyphoonComponentFactory defaultFactory];
    self.alertManager = [assembly alertManager];

    return self;
   }

Here is how I'm trying to change injection:

    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];

However tests are failing because this factory not possible to set as default. I configure in AppDelegate factory:

    TyphoonComponentFactory *factory = [[TyphoonBlockComponentFactory alloc] initWithAssemblies:@[
        [MDMainAssembly assembly],
    ]];
    [factory makeDefault];

How to get out of this situation?


回答1:


We created the defaultFactory feature for a limited number of cases. The main is:

  • Getting access to Typhoon and looking up a dependency for a class that isn't being managed by Typhoon. Generally this isn't required.

Although you could use it in tests, we recommend instead creating and destroying a Typhoon container for each test run. To avoid duplication, you could create a method as follows:

@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;
}

. . if required you could attach a patcher to this assembly.

Attaching a patcher to the default factory:

If you were to apply a patcher to the default assembly, you'd most probably want to un-patch again. This feature is in the backlog here.



来源:https://stackoverflow.com/questions/21906451/injecting-mock-with-typhoon

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!