简体   繁体   English

使用ActivityUnitTestCase和PreferenceManager对Android进行单元测试

[英]Unit Testing Android using ActivityUnitTestCase and PreferenceManager

I have an Activity I am unit testing. 我有一个Activity我是单元测试。 I want to test the Activity in isolation, so the ActivityUnitTestCase fits my purposes very well. 我想隔离测试Activity ,因此ActivityUnitTestCase非常适合我的目的。

The onCreate method of my Activity uses a value that is stored in the Preferences. 我的ActivityonCreate方法使用存储在Preferences中的值。 I would like to set a value for this in my test case. 我想在我的测试用例中为此设置一个值。

The problem is that I can't figure out how to set the Preference ahead of time. 问题是我无法弄清楚如何提前设置Preference There is not a getContext() method in ActivityUnitTestCase , and getActivity() , which should return a context , is null until I call startActivity() . ActivityUnitTestCase没有getContext()方法,并且应该返回context getActivity()在调用startActivity()之前为null。 This is not an option because calling startActivity will trigger the onCreate method, and this is where the preferences code lives. 这不是一个选项,因为调用startActivity将触发onCreate方法,这是首选项代码所在的位置。

Any thoughts on how I can get a context that I can use to manipulate the preferences for my unit tests? 有关如何获取可用于操作单元测试首选项的context任何想法?

You can get the context via the instrumentation. 您可以通过仪器获取上下文。

To get the Context of instrumentation (test runner): 获取检测的上下文(测试运行器):

getInstrumentation().getContext()

But you probably need the context of the instrumented application: 但是您可能需要已检测应用程序的上下文:

getInstrumentation().getTargetContext()

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

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