2014-02-20 48 views
2

我在寫XCTest並用颱風注入模擬依賴。用颱風注入模擬

這裏是我的ViewController代碼:

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

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

    return self; 
    } 

這裏是我正在努力改變注:

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

如何擺脫這種情況?

回答

2

我們爲有限數量的案例創建了defaultFactory特性。主要是:

  • 訪問颱風並查找不受颱風管理的類的依賴關係。通常這不是必需的。

儘管您可以在測試中使用它,但我們建議您爲每次測試運行創建並銷燬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

+0

但我的視圖控制器將如何訪問配置的工廠或我應該也將控制器實例化到工廠? –

+0

是的,我們建議使用Typhoon構建視圖控制器。然後,注入**當前用例**的依賴關係。但是對於下一個用例,請注入程序集:http://bit.ly/1nQce7k,然後查找下一個對象圖。或使用:http://bit.ly/1a93dFE或:http://bit.ly/1mdnpZ1。 。如果這不適合你,你想堅持defaultAssembly,或許一個更簡單的方法來模擬是提供一個setter,所以你可以注入一個模擬工廠。 。這取決於您是否需要配置的集成測試或純粹的單元測試。 –

+0

您是否嘗試過示例應用程序? https://github.com/typhoon-framework/Typhoon-example –