开发者

IsolatedContext vs. AndroidTestCase.getContext()

开发者 https://www.devze.com 2023-02-03 04:29 出处:网络
I\'m writing some tests to test my sqllite database code. Can someone here explain if there would be a difference writing those tests using the context I get from AndroidTestCase.getContext() or using

I'm writing some tests to test my sqllite database code. Can someone here explain if there would be a difference writing those tests using the context I get from AndroidTestCase.getContext() or using an 开发者_StackOverflow社区IsolatedContext.


For those that don't want to follow the link to the Google Group, here is the answer given there:

AndroidTestCase.getContext() returns a normal Context object. It's the Context of the test case, not the component under test.

IsolatedContext returns a "mock" Context. I put "mock" in quotes because its not a mock in the normal sense of that term (for testing). Instead, it's a template Context that you have to set up yourself. It "isolates" you from the running Android system, so that your Context or your test doesn't accidentally get outside of the test fixture. For example, an IsolatedContext won't accidentally hit a production database (unless you set it up to do that!) Note, however, that some of the methods in an IsolatedContext may throw exceptions. IsolatedContext is documented in the Developer Guide under Framework Topics > Testing, both in Testing Fundamentals and in Content Provider Testing.

Here is the Android docs on IsolatedContext.

And here is the relevant section of the Testing Fundamentals document.


The answer:

http://groups.google.com/group/android-developers/browse_thread/thread/3a7bbc78258a194a?tvc=2


I had the simple problem: I need to test my DAO class without touching the real database. So I found the IsolatedContext from docs. But finally I found the other context in the same docs: RenamingDelegatingContext might be more easier to use. Here is my test case:

public class AddictionDAOTest extends AndroidTestCase {

    @Override
    public void setUp() throws Exception {
        super.setUp();
        setContext(new RenamingDelegatingContext(getContext(), "test_"));
    }

    public void testReadAllAddictions() throws Exception {
        ImQuitDAO imQuitDAO = new ImQuitDAO(getContext());
        ...    
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消