How to inject fake, stubbed or mock dependencies for Integration tests using Typhoon

*爱你&永不变心* 提交于 2019-12-06 01:23:54

Unit Testing

If you wish to replace all dependencies for a given class with a test double, and thus test a class in isolation from its collaborators, this would be a unit test. Simply instantiate an instance for testing, passing in your test doubles (mock, stub, etc) as collaborators.

Integration Testing

If you wish to patch-out one or more instances in an assembly with a test double, to put the system into the required state for an integration test, Typhoon provides several approaches.

You can patch out a component as follows:

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]

More information on this approach can be found in the Integration Testing section of the user guide.

Modularization

Alternatively you could modularize your assembly, and activate with a sub-class or alternative implementation, that provides another implementation of certain classes, example:

UIAssembly *uiAssembly = [[UIAssembly new] 
    activateWithCollaboratingAssemblies:@[
        [TestNetworkComponents new], //<--- Patched for testing
        [PersistenceComponents new]];

SignUpViewController* viewController = [uiAssembly signUpViewController];

More information on this approach can be found in the modularization section of the user guide.

If you want to patch-out the assembly that is used by the storyboard and initialized using Plist integration, then you can make that assembly default by calling:

[yourAssembly makeDefault];

and you can get this assembly in your test case by calling:

[yourAssembly defaultAssembly];

and after that, you can easily patch some definitions. It's important to make your assembly default before test starts, so maybe app delegate will be a good place for that. This is probalby not the best solution, but it looks like you want to achieve some global access to assembly.

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