콘텐츠 제공자 테스트
컬렉션을 사용해 정리하기
내 환경설정을 기준으로 콘텐츠를 저장하고 분류하세요.
데이터를 저장 및 검색하거나 콘텐츠 제공자를 구현하여
데이터를 다른 앱에서 액세스할 수 있게 하려면 제공자를 테스트하여
예기치 않은 방식으로 작동하지 않습니다. 이 강의에서는 공개 IP 주소를 테스트하는 방법을
콘텐츠 제공업체에도 적용됩니다.
있습니다.
콘텐츠 제공업체의 통합 테스트 만들기
콘텐츠 제공자를 통해 실제 사용자 데이터에 액세스할 수 있으므로
테스트해야 합니다. 이
이 접근 방식을 사용하면
테스트 사례입니다. 또한 테스트에서 실제 사용자 데이터를 수정하지 않습니다. 대상
예를 들어 테스트가 실패하는 테스트는 작성해서는 안 되며 그 이유는
이전 테스트에서 가져온 것입니다. 마찬가지로 테스트는
실제 연락처 정보가 포함되어 있습니다.
개별적으로 콘텐츠 제공업체를 테스트하려면 ProviderTestCase2
를 사용하세요.
클래스에 대해 자세히 알아보세요. 이 클래스를 통해 다음과 같은 Android 모의 객체 클래스를 사용할 수 있습니다.
파일에 액세스하기 위한 IsolatedContext
및 MockContentResolver
데이터베이스 정보를 식별할 수 있습니다.
통합 테스트는 JUnit 4 테스트 클래스로 작성해야 합니다. 자세히 알아보기
JUnit 4 테스트 클래스를 만들고 JUnit 4 어설션을 사용하는 방법을 보려면
로컬 단위 테스트 클래스를 참조하세요.
콘텐츠 제공업체의 통합 테스트를 만들려면 다음을 실행해야 합니다.
단계:
- 테스트 클래스를
ProviderTestCase2
의 서브클래스로 만듭니다.
- AndroidX 테스트에서 제공하는
AndroidJUnitRunner
클래스를 지정합니다.
를 기본 테스트 실행기로 사용하세요.
ApplicationProvider
클래스에서 Context
객체를 설정합니다. 자세한 내용은
아래 스니펫을 참고하세요.
Kotlin
@Throws(Exception::class)
override fun setUp() {
super.setUp()
context = ApplicationProvider.getApplicationContext<Context>()
}
자바
@Override
protected void setUp() throws Exception {
super.setUp();
setContext(ApplicationProvider.getApplicationContext());
}
ProviderTestCase2 작동 방식
ProviderTestCase2
의 서브클래스를 사용하여 제공업체를 테스트합니다. 이 기본 클래스는
AndroidTestCase
를 확장하므로 JUnit 테스트 프레임워크를 다음과 같이 제공합니다.
애플리케이션 권한 테스트를 위한 Android 전용 메서드도 제공합니다. 가장
이 클래스의 중요한 특징은 초기화이며,
테스트 환경을 제공합니다
초기화
초기화는 ProviderTestCase2
의 생성자에서 실행됩니다.
서브클래스가 자체 생성자에서 호출하는 클래스입니다. ProviderTestCase2
생성자가 파일과 객체를 허용하는 IsolatedContext
객체를 만듭니다.
Android 시스템과의 다른 상호작용을 스텁 처리합니다.
파일 및 데이터베이스 작업 자체는
로컬 기기 또는 에뮬레이터에 로컬이며, 특수 접두사가 있습니다.
그런 다음 생성자가 리졸버로 사용할 MockContentResolver
를 만듭니다.
입니다.
마지막으로 생성자는 테스트 중인 제공업체의 인스턴스를 만듭니다. 이것은
일반적인 ContentProvider
객체이지만 이 객체의 모든 환경을 사용합니다.
기밀 IsolatedContext
설계하는 방법을 알아봅니다 테스트 사례 클래스에서 실행된 모든 테스트는
대비할 수 있습니다
계측된 것과 동일한 방식으로 콘텐츠 제공업체의 통합 테스트를 실행합니다.
단위 테스트와 유사합니다.
테스트 대상
다음은 콘텐츠 제공업체를 테스트하기 위한 구체적인 가이드라인입니다.
- 리졸버 메서드로 테스트: 제공업체를 인스턴스화할 수 있더라도
객체
ProviderTestCase2
에서는 항상 다음을 사용하여 리졸버 객체로 테스트해야 합니다.
적절한 URI입니다. 이렇게 하면 다음을 통해 제공업체를 테스트할 수 있습니다.
일반 애플리케이션이 사용하는 것과 동일한 상호 작용을 수행하고 있을 수 있습니다.
- 공개 제공업체를 계약으로 테스트: 제공업체를 대상으로 하는 경우
공개되어 다른 애플리케이션에서 사용할 수 있는 경우 계약으로 테스트해야 합니다.
다음과 같은 방법을 사용할 수 있습니다.
<ph type="x-smartling-placeholder">
</ph>
- 제공업체가 공개적으로 노출하는 상수로 테스트합니다. 예를 들어
제공자의 데이터 테이블 중 하나에서 열 이름을 참조하는 상수.
이러한 상수는 항상 제공업체가 공개적으로 정의한 상수여야 합니다.
- 제공업체가 제공하는 모든 URI 테스트: 제공업체에 따라
URI는 각각 데이터의 다른 측면을 나타냅니다.
- 잘못된 URI를 테스트합니다. 단위 테스트는 의도적으로 제공업체를 다음과 같이 호출해야 합니다.
잘못된 URI를 찾고 오류를 찾습니다. 좋은 제공업체 디자인은
IllegalArgumentException
: 잘못된 URI
- 표준 제공자 상호작용 테스트: 대부분의 제공업체는 6개의 액세스를 제공합니다.
메서드:
query()
, insert()
, delete()
, update()
, getType()
,
onCreate()
테스트를 통해 이러한 모든 메서드가 작동하는지 확인해야 합니다.
- 비즈니스 로직 테스트: 콘텐츠 제공업체가 비즈니스 로직을 구현하는 경우
나
테스트해야 합니다 비즈니스 로직에는 잘못된 값, 재무 또는
산술 계산, 소거 또는 중복 연산 결합 등입니다.
이 페이지에 나와 있는 콘텐츠와 코드 샘플에는 콘텐츠 라이선스에서 설명하는 라이선스가 적용됩니다. 자바 및 OpenJDK는 Oracle 및 Oracle 계열사의 상표 또는 등록 상표입니다.
최종 업데이트: 2025-07-27(UTC)
[[["이해하기 쉬움","easyToUnderstand","thumb-up"],["문제가 해결됨","solvedMyProblem","thumb-up"],["기타","otherUp","thumb-up"]],[["필요한 정보가 없음","missingTheInformationINeed","thumb-down"],["너무 복잡함/단계 수가 너무 많음","tooComplicatedTooManySteps","thumb-down"],["오래됨","outOfDate","thumb-down"],["번역 문제","translationIssue","thumb-down"],["샘플/코드 문제","samplesCodeIssue","thumb-down"],["기타","otherDown","thumb-down"]],["최종 업데이트: 2025-07-27(UTC)"],[],[],null,["# Test content providers\n\nIf you are implementing a [content provider](/guide/topics/providers/content-providers) to store and retrieve data or to\nmake data accessible to other apps, you should test your provider to ensure that\nit doesn't behave in an unexpected way. This lesson describes how to test public\ncontent providers, and is also applicable to providers that you keep private to\nyour own app.\n\nCreate integration tests for content providers\n----------------------------------------------\n\nContent providers let you access actual user data, so it's important to ensure\nthat you test the content provider in an isolated testing environment. This\napproach allows you to only run against data dependencies set explicitly in the\ntest case. It also means that your tests do not modify actual user data. For\nexample, you should avoid writing a test that fails because there was data left\nover from a previous test. Similarly, your test should avoid adding or deleting\nactual contact information in a provider.\n| **Note:** This document focuses on [`ProviderTestCase2`](/reference/android/test/ProviderTestCase2) which is being replaced by the experimental [`ProviderTestRule`](/reference/androidx/test/rule/provider/ProviderTestRule).\n\nTo test your content provider in isolation, use the `ProviderTestCase2`\nclass. This class allows you to use Android mock object classes such as\n[`IsolatedContext`](/reference/android/test/IsolatedContext) and [`MockContentResolver`](/reference/android/test/mock/MockContentResolver) to access file and\ndatabase information without affecting the actual user data.\n\nYour integration test should be written as a JUnit 4 test class. To learn more\nabout creating JUnit 4 test classes and using JUnit 4 assertions, see [Create a\nLocal Unit Test Class](/training/testing/local-tests#test-class).\n\nTo create an integration test for your content provider, you must perform these\nsteps:\n\n1. Create your test class as a subclass of `ProviderTestCase2`.\n2. Specify the [`AndroidJUnitRunner`](/reference/androidx/test/runner/AndroidJUnitRunner) class that [AndroidX Test](/training/testing) provides as your default test runner.\n3. Set the [`Context`](/reference/android/content/Context) object from the `ApplicationProvider` class. See the snippet below for an example.\n\n### Kotlin\n\n```kotlin\n@Throws(Exception::class)\noverride fun setUp() {\n super.setUp()\n context = ApplicationProvider.getApplicationContext\u003cContext\u003e()\n}\n```\n\n### Java\n\n```java\n@Override\nprotected void setUp() throws Exception {\n super.setUp();\n setContext(ApplicationProvider.getApplicationContext());\n}\n```\n\n### How ProviderTestCase2 works\n\nYou test a provider with a subclass of `ProviderTestCase2`. This base class\nextends [`AndroidTestCase`](/reference/android/test/AndroidTestCase), so it provides the JUnit testing framework as\nwell as Android-specific methods for testing application permissions. The most\nimportant feature of this class is its initialization, which creates the\nisolated test environment.\n\n#### Initialization\n\nThe initialization is done in the constructor for `ProviderTestCase2`,\nwhich subclasses call in their own constructors. The `ProviderTestCase2`\nconstructor creates an `IsolatedContext` object that allows file and\ndatabase operations but stubs out other interactions with the Android system.\nThe file and database operations themselves take place in a directory that is\nlocal to the device or emulator and has a special prefix.\n\nThe constructor then creates a `MockContentResolver` to use as the resolver\nfor the test.\n\nLastly, the constructor creates an instance of the provider under test. This is\na normal [`ContentProvider`](/reference/android/content/ContentProvider) object, but it takes all of its environment\ninformation from the `IsolatedContext`, so it is restricted to working in\nthe isolated test environment. All of the tests done in the test case class run\nagainst this isolated object.\n\nYou run integration tests for content providers the same way as instrumented\nunit tests.\n\nWhat to test\n------------\n\nHere are some specific guidelines for testing content providers.\n\n- **Test with resolver methods** : Even though you can instantiate a provider object in `ProviderTestCase2`, you should always test with a resolver object using the appropriate URI. Doing so ensures that you are testing the provider by performing the same interaction that a regular application would use.\n- **Test a public provider as a contract** : If you intend your provider to be public and available to other applications, you should test it as a contract. Some examples of how to do so are as follows:\n - Test with constants that your provider publicly exposes. For example, look for constants that refer to column names in one of the provider's data tables. These should always be constants publicly defined by the provider.\n - Test all the URIs that your provider offers. Your provider may offer several URIs, each one referring to a different aspect of the data.\n - Test invalid URIs. Your unit tests should deliberately call the provider with an invalid URI, and look for errors. A good provider design is to throw an `IllegalArgumentException` for invalid URIs.\n- **Test the standard provider interactions** : Most providers offer six access methods: `query()`, `insert()`, `delete()`, `update()`, `getType()`, and `onCreate()`. Your tests should verify that all of these methods work.\n- **Test business logic**: If the content provider implements business logic, you should test it. Business logic includes handling of invalid values, financial or arithmetic calculations, elimination, or combining of duplicates."]]