Ios 使用OCMock进行单元测试本地对象还是依赖项注入?
正在尝试为以下函数创建简单测试:Ios 使用OCMock进行单元测试本地对象还是依赖项注入?,ios,unit-testing,ocmock,Ios,Unit Testing,Ocmock,正在尝试为以下函数创建简单测试: -(void)presentWithString:(NSString *)name { CustomVC *customVC = [[CustomVC alloc] initWithName:name]; UINavigationController *nav = [[UINavigationController alloc] init]; nav.viewControllers = @[customVC]; dispatch_
-(void)presentWithString:(NSString *)name
{
CustomVC *customVC = [[CustomVC alloc] initWithName:name];
UINavigationController *nav = [[UINavigationController alloc] init];
nav.viewControllers = @[customVC];
dispatch_async(dispatch_get_main_queue(), ^{
[self.vc presentViewController:nav animated:YES completion:nil];
});
}
我可以用依赖项注入将其分割成块,但不知道如何编写适当的测试。本例的最佳实践是什么?您希望测试什么?在您的方法中发生了三件事:
CustomVC
是在传递了name
的情况下创建的CustomVC
嵌入在导航控制器中self.vc
上- (void)testPresentWithString_shouldPresentCustomVC_withPassedName {
// Arrange
NSString *expectedName = @”name”;
XCTestExpectation *exp = [self expectationWothDescription:@”presentVC called”];
TestClass *sut = [[TestClass alloc] init];
id vcMock = OCMClassMock([UIViewController class]);
sut.vc = vcMock;
OCMExpect([vcMock presentViewController:OCM_ANY animated:YES completion:nil]).andDo(^(NSInvocation *invocation) {
UINavigationController *nav = nil;
[invocation getArgument:&nav atIndex:2];
CustomVC *custom = nav.viewControllers.firstObject;
// Assert
XCTAssertNotNil(nav);
XCTAssertTrue([nav isKindOfClass:[UINavigationController class]]);
XCTAssertEqual(nav.viewControllers.count, 1);
XCTAssertNotNil(custom);
XCTAssertTrue([custom isKindOfClass:[CustomVC class]]);
XCTAssertEqual(custom.name, expectedName);
[exp fulfill];
});
// Act
[sut presentWithString:expectedName];
// Assert
[self waitForExpectationsWithTimeout:1 handler:nil];
OCMVerifyAll(vcMock);
// Cleanup
[vcMock stopMocking];
}
此代码检查方法中发生的所有情况—是否使用特定参数调用了方法,这些参数中的第一个参数是否是只嵌入了CustomVC
的导航控制器,以及此CustomVC
是否设置了name
。显然,我已经假设测试类上的vc
属性可以从外部设置,并且CustomVC
上的name
可以读取。如果不是的话,测试其中的某些部分可能会更加棘手
就我个人而言,我不会对此进行单元测试。我将分别测试CustomVC
的初始化,并对整个演示文稿进行UI测试
如果一切都清楚,请告诉我
-
旁注:我是在手机上用内存写的,所以代码中可能有一些小错误。当我有机会用Xcode检查它时,我会更新它。谢谢,它可以工作。但当我尝试编写单独的函数和测试时,结果是[ocmockobjectdealloc]错误。在你看来,你能更新你的答案并写出创建函数和测试的正确方法吗?我已经陈述了我的观点-我不会对这个方法进行单元测试。这似乎应该是由于用户交互而发生的,对吗?如果是这样的话,它属于UI测试。至于ubit测试,我只测试
CustomVC
初始值设定项。