0

我在启动和运行我的测试套件时遇到了一些麻烦。基本上我向我的应用程序添加了一个新目标,如下所示: 单元测试应用程序

当我想针对我的 DA 类和 sqlite-database 进行测试时,我使用以下片段来复制数据库:

    // First, test for existence.
BOOL success;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:DATABASE_Path];
success = [fileManager fileExistsAtPath:writableDBPath];
if (success) return;
// The writable database does not exist, so copy the default to the appropriate location.
NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:DATABASE_Path];
success = [fileManager copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error];
if (!success) {
    NSAssert1(0, @"Failed to create writable database file with message '%@'.", [error localizedDescription]);
}

但看起来,NSBundle 并没有按预期返回数据库的路径。

有一个简单的解决方法吗?在过去的几个小时里我没能修好它——所以我的下一个镜头就是你们。

任何帮助或建议都非常感谢!

非常感谢!

汤姆

4

1 回答 1

1

我刚刚遇到了完全相同的问题,继承了一些以非常相似的方式进行原始 sqlite 访问的代码。

这里有两个问题,他们在其他地方回答了 SO。

首先,在测试期间 NSBundle mainBundle 不会返回您认为的结果,如果您希望依赖于 NSBundle mainBundle 的代码在单元测试期间工作,您可以将其替换为

[NSBundle bundleForClass: [self class]]

我不确定这是否效率更低(可能),但它在单元测试中确实有效。

第二个问题是文档目录没有被正确引用,因为单元测试没有在沙箱内运行。有几种方法可以解决这个问题,但最简单的方法是在 ~/Library/Application Support/iPhone Simulator/6.1/ 中创建一个文档目录。显然,6.1 只是一个例子。

参考:-

OCUnit & NSBundle

iPhone单元测试中的NSHomeDirectory

顺便说一句,我只是喜欢回答老问题。

于 2013-08-29T09:35:45.997 回答