简体   繁体   English

iPhone单元测试中的NSHomeDirectory

[英]NSHomeDirectory in iPhone unit test

When using NSHomeDirectory() inside a unit test I get: 在单元测试中使用NSHomeDirectory()我得到:

/Users/hgpc/Library/Application Support/iPhone Simulator/5.0

I expected the actual home directory of the current application. 我期望当前应用程序的实际主目录。 Something like: 就像是:

/Users/hgpc/Library/Application Support/iPhone Simulator/5.0/Applications/6D1091C6-02AE-4803-A7DF-D623D0F89579

What am I doing wrong? 我究竟做错了什么?

To solve this, set the value of Bundle Loader within your Unit Test target build settings to: 要解决此问题,请将Unit Test目标构建设置中的Bundle Loader值设置为:

$(BUILT_PRODUCTS_DIR)/MyAppName.app/MyAppName

and also your Test Host to: 以及你的测试主持人:

$(BUNDLE_LOADER)

you should then find NSHomeDirectory() returns the right value. 然后你应该找到NSHomeDirectory()返回正确的值。

Unfortunately, while in a unit-test (or logic test) - you're not really "in your app" (ie its sandbox). 不幸的是,在单元测试(或逻辑测试)中 - 你并不是真的“在你的应用程序中”(即它的沙盒)。 That's why stuff like NSDocumentDirectory or [NSBundle mainBundle] will not work. 这就是NSDocumentDirectory或[NSBundle mainBundle]之类的东西无效的原因。

If it works for you, I'd just go ahead and create a "Documents" folder in 如果它适合你,我会继续创建一个“Documents”文件夹

/Users/hgpc/Library/Application Support/iPhone Simulator/5.0

You might want to do this in your test's setUp, that way you can delete it in tearDown. 您可能希望在测试的setUp中执行此操作,这样您就可以在tearDown中删除它。

If that doesn't work because your tests depend on stuff already being in your app's NSDocumentDirectory, you might want to re-think your test a little, as they should all be self-contained (ie install all resources from your bundle in setUp) 如果这不起作用,因为您的测试依赖于已经存在于您的应用程序的NSDocumentDirectory中的内容,您可能需要重新考虑一下您的测试,因为它们都应该是自包含的(即在setUp中安装捆绑包中的所有资源)

You could also use NSLibraryDirectory instead of NSDocumentDirectory, depending on what it is that you want to test. 您也可以使用NSLibraryDirectory而不是NSDocumentDirectory,具体取决于您要测试的内容。

If you'd like to customised your test target to Application test you should add params mentioned by Andrew Ebling: 如果您想将测试目标定制到Application test,您应该添加Andrew Ebling提到的params:

 $(BUILT_PRODUCTS_DIR)/MyAppName.app/MyAppName 

and also your Test Host to: 以及你的测试主持人:

 $(BUNDLE_LOADER) 

If you don't have this params that means your tests is logic. 如果你没有这个参数,那意味着你的测试是逻辑的。 But if you add this params you change tests to Application tests and notice that AppDelegate will start did you run tests. 但是如果你添加这个参数你将测试更改为应用程序测试,并注意到AppDelegate将启动你是否运行测试。

see link for more information. 请参阅链接以获取更多信息

So you can use NSHomeDirectory( for Application tests only. 因此,您可以使用NSHomeDirectory(仅适用于应用程序测试)。

On an iOS device you should use 在iOS设备上,您应该使用

NSArray *path = NSSearchPathForDirectoriesInDomains(
            NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentDirPath = [paths objectAtIndex:0];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM