gpt4 book ai didi

ios - TyphoonPatcher 用于单元测试中的模拟

转载 作者:塔克拉玛干 更新时间:2023-11-02 09:27:56 24 4
gpt4 key购买 nike

我有程序集:

@interface MDUIAssembly : TyphoonAssembly

@property (nonatomic, strong, readonly) MDServiceAssembly *services;
@property (nonatomic, strong, readonly) MDModelAssembly *models;

- (id)choiceController;

@end

@implementation MDUIAssembly

- (void)resolveCollaboratingAssemblies
{
_services = [TyphoonCollaboratingAssemblyProxy proxy];
_models = [TyphoonCollaboratingAssemblyProxy proxy];
}

- (id)choiceController
{
return [TyphoonDefinition withClass:[MDChoiceViewController class]
configuration: ^(TyphoonDefinition *definition) {
[definition useInitializer:@selector(initWithAnalytics:diary:)
parameters: ^(TyphoonMethod *initializer) {
[initializer injectParameterWith:[_services analytics]];
[initializer injectParameterWith:[_models diary]];
}];
}];
}

@end

这是我在测试中尝试做的事情:

- (void)setUp
{
patcher = [TyphoonPatcher new];
MDUIAssembly *ui = (id) [TyphoonComponentFactory defaultFactory];
[patcher patchDefinition:[ui choiceController] withObject:^id{
return mock([MDChoiceViewController class]);
}];
[[TyphoonComponentFactory defaultFactory] attachPostProcessor:patcher];
}

- (void) tearDown
{
[super tearDown];
[patcher rollback];
}

不幸的是,我的setUp 失败并显示下一条消息:

-[MDChoiceViewController key]: unrecognized selector sent to instance 0xbb8aaf0

我做错了什么?

最佳答案

您在 Typhoon 方面遇到了糟糕的设计选择,但有一个简单的解决方法。

你正在使用这个方法:

[patcher patchDefinition:[ui choiceController] withObject:^id{
return mock([MDChoiceViewController class]);
}];

. .期望 TyphoonDefinition 作为参数。引导台风时:

  • 我们从一个或多个 TyphoonAssembly 子类开始,Typhoon 使用这些子类来获取构建组件的方法。然后丢弃这些 TyphoonAssembly 子类。
  • 我们现在有一个 TyphoonComponentFactory,它将允许您的任何 TyphoonAssembly 接口(interface)在它前面pose . (这样你就可以拥有同一个类的多个配置,同时仍然避免魔术字符串,允许在你的 IDE 中自动完成等)。

编写 TyphoonPatcher 时,它是为您为测试获取新的 TyphoonComponentFactory 的情况而设计的(推荐),如下所示:

//This is an actual TyphoonAssembly not the factory posing as an assembly
MiddleAgesAssembly* assembly = [MiddleAgesAssembly assembly];

TyphoonComponentFactory* factory = [TyphoonBlockComponentFactory factoryWithAssembly:assembly];

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

return mockKnight;
}];

[factory attachPostProcessor:patcher];
Knight* knight = [(MiddleAgesAssembly*) factory knight];

发生了什么:

所以问题是 TyphoonPatcher 期望来自 TyphoonAssemblyTyphoonDefinition 而不是从 获取实际组件台风组件工厂

非常困惑,应该弃用这种获取补丁程序的方式。

解决方案:

请改用以下内容:

[patcher patchDefinitionWithSelector:@selector(myController) withObject:^id{
return myFakeController;
}];

关于ios - TyphoonPatcher 用于单元测试中的模拟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24956211/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com