Where does OCUnit store NSUserDefaults?

2019-07-24 20:11发布

I read the question Easy way to see saved NSUserDefaults?

I found the .plist file for the app, but where's the one for the testing bundle?

3条回答
闹够了就滚
2楼-- · 2019-07-24 20:26

It seems that OCUnit doesn't store NSUserDefaults persistently but rather in memory. But, I could be wrong.

查看更多
贼婆χ
3楼-- · 2019-07-24 20:45

In my environment (Xcode 4.2, running tests in the simulator) NSUserDefaults writes to the following file:

~/Library/Application Support/iPhone Simulator/Library/Preferences/otest.plist`

I guess you didn't see the file because of NSUserDefaults's caching mechanism (explained in the class reference), and because your project's unit tests do not run long enough for the caching time interval to elapse.

otest.plist is guaranteed to be written, though, if something invokes the NSUserDefault instance method synchronize while the tests are running.

查看更多
戒情不戒烟
4楼-- · 2019-07-24 20:46

If you use Xcode 4's integration with OCUnit, it injects the test bundle into a running application. NSUserDefaults are therefore saved in the application itself. This is problematic for unit tests: When you run the app manually, your defaults may have been overwritten by your tests.

Instead of using [NSUserDefaults standardUserDefaults] directly, use dependency injection, passing in user defaults as an initializer argument. Then you can pass in a test double that you can query. (An alternative to dependency injection is returning NSUserDefaults from a helper method, overriding that method to return the test double when necessary.)

查看更多
登录 后发表回答