NSHomeDirectory in iPhone unit test

2019-01-18 14:26发布

When using NSHomeDirectory() inside a unit test I get:

/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?

4条回答
Juvenile、少年°
2楼-- · 2019-01-18 14:37

On an iOS device you should use

NSArray *path = NSSearchPathForDirectoriesInDomains(
            NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentDirPath = [paths objectAtIndex:0];
查看更多
淡お忘
3楼-- · 2019-01-18 14:40

Unfortunately, while in a unit-test (or logic test) - you're not really "in your app" (i.e. its sandbox). That's why stuff like NSDocumentDirectory or [NSBundle mainBundle] will not work.

If it works for you, I'd just go ahead and create a "Documents" folder in

/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.

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 (i.e. install all resources from your bundle in setUp)

You could also use NSLibraryDirectory instead of NSDocumentDirectory, depending on what it is that you want to test.

查看更多
Explosion°爆炸
4楼-- · 2019-01-18 14:46

If you'd like to customised your test target to Application test you should add params mentioned by Andrew Ebling:

$(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.

see link for more information.

So you can use NSHomeDirectory( for Application tests only.

查看更多
乱世女痞
5楼-- · 2019-01-18 14:59

To solve this, set the value of Bundle Loader within your Unit Test target build settings to:

$(BUILT_PRODUCTS_DIR)/MyAppName.app/MyAppName

and also your Test Host to:

$(BUNDLE_LOADER)

you should then find NSHomeDirectory() returns the right value.

查看更多
登录 后发表回答