Programing

컨텍스트가 필요한 Android 단위 테스트

lottogame 2020. 12. 9. 07:38
반응형

컨텍스트가 필요한 Android 단위 테스트


첫 번째 Android 데이터베이스 백엔드를 작성 중이며 데이터베이스 생성을 단위 테스트하는 데 어려움을 겪고 있습니다.

현재 내가 겪고있는 문제는 SQLiteOpenHelper 구현에 전달할 유효한 Context 객체를 얻는 것입니다. TestCase를 확장하는 클래스에서 Context 객체를 얻는 방법이 있습니까? 내가 생각한 해결책은 내 TestCase의 설정 메소드에서 활동을 인스턴스화 한 다음 해당 활동의 컨텍스트를 내 테스트 메소드가 액세스 할 수있는 필드 변수에 할당하는 것입니다 ...하지만 더 쉬운 방법이있는 것 같습니다.

입력 해 주셔서 감사합니다!

메이시


AndroidTestCase로 전환 해 볼 수 있습니다 . 문서를 살펴보면 SQLiteOpenHelper에 전달할 유효한 컨텍스트를 제공 할 수있을 것 같습니다.

편집 : 테스트가 에뮬레이터 (또는 실제 장치)에서 실행을 시도하므로 Eclipse의 "Android 테스트 프로젝트"에서 테스트를 설정해야 할 수 있습니다.


InstrumentationRegistry메소드를 사용 하여 컨텍스트를 가져올 수 있습니다 .

InstrumentationRegistry.getTargetContext()- Context대상 애플리케이션 의 애플리케이션 제공합니다 .

InstrumentationRegistry.getContext()- Context이 Instrumentation의 패키지를 제공합니다 .


AndroidX의 경우 InstrumentationRegistry.getInstrumentation().getTargetContext()또는 InstrumentationRegistry.getInstrumentation().getContext().


AndroidTestCase:getContext()방법을 사용하면 내 경험에서 스텁 컨텍스트 만 제공됩니다. 내 테스트를 위해 메인 앱에서 빈 활동을 사용하고 Context있습니다. 또한 클래스와 함께 테스트 스위트 클래스를 확장하고 ActivityInstrumentationTestCase2있습니다. 나를 위해 일하는 것 같습니다.

public class DatabaseTest extends ActivityInstrumentationTestCase2<EmptyActivity>
    EmptyActivity activity;
    Context mContext = null;
    ...
    @Before
    public void setUp() {
        activity = getActivity();
        mContext = activity;
    }
    ... //tests to follow
}

다른 사람들은 무엇을합니까?


ApplicationTestCase 또는 ServiceTestCase를 사용해야합니다.


MockContext 에서 파생되어 예를 들어 MockResources on getResources(), 유효한 ContentResolver on getContentResolver()등을 반환 할 수 있습니다 . 이렇게하면 약간의 고통과 함께 일부 단위 테스트가 허용 됩니다.

대안은 전체 Android OS를 시뮬레이션하는 Robolectric 을 실행 하는 것입니다. 시스템 테스트를 위한 것 입니다. 실행 속도가 훨씬 느립니다.


AndroidTestCase를 확장하고 AndroidTestCase : getContext ()를 호출하면 Context를 가져와 SQLiteDatabase와 함께 사용하는 데 문제가 없습니다.

유일한 문제는 생성 및 / 또는 사용하는 데이터베이스가 프로덕션 응용 프로그램에서 사용하는 데이터베이스와 동일하므로 둘 다에 대해 다른 파일 이름을 사용하고 싶을 것입니다.

예.

  public static final String    NOTES_DB      = "notestore.db";
  public  static final String   DEBUG_NOTES_DB = "DEBUG_notestore.db";

당신의 테스트는 단위 테스트가 아닙니다 !!!

필요할 때

  • 문맥
  • 스토리지에서 읽기 또는 쓰기
  • 액세스 네트워크
  • 또는 기능을 테스트하기 위해 구성을 변경하십시오.

단위 테스트를 작성하지 않습니다.

androidTest패키지에 테스트를 작성해야 합니다.


먼저 (androidTest)에서 테스트 클래스를 만듭니다.

이제 다음 코드를 사용하십시오.

public class YourDBTest extends InstrumentationTestCase {

private DBContracts.DatabaseHelper db;
private RenamingDelegatingContext context;

@Override
public void setUp() throws Exception {
    super.setUp();
    context = new RenamingDelegatingContext(getInstrumentation().getTargetContext(), "test_");
    db = new DBContracts.DatabaseHelper(context);
}

@Override
public void tearDown() throws Exception {
    db.close();
    super.tearDown();
}

@Test
public void test1() throws Exception {
    // here is your context
    context = context;
}}

대체 솔루션은 회피의 사용에있다 ApplicationTestCase거나 AndroidTestCase또는 의존하는 다른 클래스 Context. 요점은 테스트 SQLiteORM프레임 워크 가 필요하지 않으므로 기본 CRUD메서드로 인터페이스를 만들 수 있다는 것입니다 .

public interface UsersManager{
  User createUser(String userId);
  User getUser(String userId);
  boolean updateUser(User user);
  boolean deleteUser(User user);
}

그리고 두 가지 버전을 구현합니다. 하나는 테스트 용이고 다른 하나는 프로덕션 런타임 용입니다. 테스트 용 버전은 다음을 사용하여 쉽게 구현할 수 있습니다 HashMap.

public class TestUsersManager implements UsersManager{

  private HashMap<String, User> users = new HashMap();

  public User createUser(String userId){
    User result = new User(userId);
    users.put(userId, user);
    return result;
  }
  //... other methods
}

It works fast (no disk IO in case of SQLite) and doesn't have external dependencies. By the way this is also additional level of abstraction: for production code you could easily switch between ORM frameworks for instance.

참고URL : https://stackoverflow.com/questions/2095695/android-unit-tests-requiring-context

반응형