[英]Is there any way to test classes that access ContentResolver with JUnit? Or do I have to use Robolectric?
I have a test class like this: 我有一个像这样的测试班:
public class PostRepositoryTest extends AndroidTestCase {
Context context;
@Before
public void setUp() throws Exception {
context = new Application();
}
@Test
public void testFindAll() {
PostRepository postRepository = PostRepository.get(context);
List<Post> all = postRepository.findAll();
assertEquals(0, all.size());
}
}
findAll
method just uses a ContentResolver to return results from a ContentResolver. findAll
方法仅使用ContentResolver从ContentResolver返回结果。
public List<Post> findAll() {
Cursor c = new PostSelection().query(context.getContentResolver());
return listFromCursor(c);
}
Before trying this way... I was doing this by using AndroidInstrumentationTestCase2
and launching an activity to check all of those things, but I want to avoid that. 在尝试这种方式之前...我是通过使用AndroidInstrumentationTestCase2
并启动一个活动来检查所有这些内容的方式来进行此操作的,但是我想避免这种情况。
I'd like to do this as an unit test. 我想以此作为单元测试。 Is it possible? 可能吗?
It depends whether you want to run this test case on a device or not. 这取决于您是否要在设备上运行此测试用例。 Go for Robolectric if you want to run it on local JVM instead of running on device. 如果要在本地JVM上而不是在设备上运行,请选择Robolectric。 If you want to run on device without AndroidInstrumentationTestCase2, then you can use AndroidJUnitRunner. 如果要在没有AndroidInstrumentationTestCase2的设备上运行,则可以使用AndroidJUnitRunner。 Its based on Junit4 specification. 它基于Junit4规范。 Read the link here: https://developer.android.com/training/testing/unit-testing/instrumented-unit-tests.html 在此处阅读链接: https : //developer.android.com/training/testing/unit-testing/instrumented-unit-tests.html
See the code samples for basic idea: https://github.com/googlesamples/android-testing/tree/master/unittesting/BasicUnitAndroidTest 请参阅代码示例以获取基本思想: https : //github.com/googlesamples/android-testing/tree/master/unittesting/BasicUnitAndroidTest
If you setup your test suite according to the above link then you don't need to extend any class or launch an activity. 如果您根据上述链接设置了测试套件,则无需扩展任何类或启动任何活动。 You can get context object using the code: 您可以使用以下代码获取上下文对象:
InstrumentationRegistry.getTargetContext();
or
InstrumentationRegistry.getContext();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.