我只是在理解TDD和嘲笑的概念,並且正在就如何正確處理問題。我有一張表單,可以讓用戶創建一個新的核心數據對象並將其保存到數據存儲中。我不確定我是否正在採取最好的方法來測試它。使用OCMock和核心數據測試控制器方法
- (IBAction)add:(id)sender
{
NSString *itemName = [self.itemNameTextField stringValue];
SGItem *newItem = [NSEntityDescription insertNewObjectForEntityForName:kItemEntityName inManagedObjectContext:[self managedObjectContext]];
newItem.name = itemName;
NSError *error = nil;
BOOL canSaveNewItem = [[self managedObjectContext] save:&error];
if (!canSaveNewItem)
{
[NSApp presentError:error];
}
[self clearFormFields]; // Private method that clears text fields, disables buttons
[NSApp endSheet:[self window] returnCode:NSOKButton];
}
我試着寫兩個測試方法來測試:一個測試場景,其中的管理對象不能保存或一個地方成功保存。
@interface SGAddItemWindowControllerTests : SGTestCase
{
@private
SGAddItemWindowController *addItemWindowController;
id mockApp;
id mockNameField;
}
- (void)setUp
{
mockNameField = [OCMockObject mockForClass:[NSTextField class]];
mockApp = [OCMockObject mockForClass:[NSApplication class]];
addItemWindowController = [[BLAddItemWindowController alloc] init];
[addItemWindowController setValue:mockNameField forKey:@"itemNameTextField"];
}
- (void)testAddingNewItemFromSheetFailed
{
// Setup
NSString *fakeName = @"";
[[[mockNameField expect] andReturn:fakeName] stringValue];
[[mockApp expect] presentError:[OCMArg any]];
// Execute
[addItemWindowController add:nil];
// Verify
[mockApp verify];
}
- (void)testAddingNewItemFromSheetSucceeds
{
// Setup
NSString *fakeName = @"Item Name";
[[[mockNameField expect] andReturn:fakeName] stringValue];
[[mockApp expect] endSheet:[OCMArg any] returnCode:NSOKButton];
// Execute
[addItemWindowController add:nil];
// Verify
[mockApp verify];
[mockNameField verify];
}
@end
這裏是我知道我有問題,但我不知道如何工作的:
- 我不知道如何處理與被管理對象上下文在測試方面的處理。我應該提出整個核心數據堆棧還是創建一個
NSManagedObjectContext
的模擬? - 只是將文本字段值設置爲觸發if語句的方式似乎是錯誤的想法。理想情況下,我認爲我應該將方法剔除並返回YES或NO,但給出問題1我不確定它的核心數據方面。
我認爲我在正確的軌道上,但是我可以對如何解決我的問題並將我設置在測試代碼段的正確路徑上使用第二種意見。