Trong bài trước, tôi mô tả cách dùng Proto DataStore trong ứng dụng. Tôi viết bài đó như một phần của kinh nghiệm dùng Proto DataStore trong một ứng dụng của mình.
Sau đó, tôi muốn xem viết test cho Proto DataStore trong ứng dụng đó dùng kiến thức vừa học sẽ như thế nào.
Tìm kiếm online không giúp ích nhiều, nên tôi quyết định chia sẻ kiến thức cho những ai đang tìm kiếm. Tồi nhất, nó dành cho con cháu tôi.
Trong tìm kiếm, tôi tìm thấy bài này, nhưng tập trung chủ yếu vào test Preferences DataStore chứ không phải Proto DataStore. Nó nói rằng:
“Tuy nhiên, hãy nhớ bạn có thể dùng tài liệu này để setup test Proto DataStore, vì nó sẽ rất giống Preferences.”
Nhưng làm theo, tôi thấy ngoài dependencies, không có nhiều điểm giống nhau và bạn cần đưa logic riêng để test Proto DataStore của mình.
Thiết lập mọi thứ
Trong file build.gradle cấp ứng dụng, thêm dependencies sau:
dependencies { ///..... androidTestImplementation "androidx.compose.ui:ui-test-junit4:$compose_version" debugImplementation "androidx.compose.ui:ui-test-manifest:$compose_version" }
$compose_version là biến bạn định nghĩa trong build.gradle cấp dự án.
Sau đó, vào thư mục androidTest và tạo file mới. Thường bạn sẽ có class repository tương tác với Proto DataStore, nên đặt tên file là YourRepositoryClassNameTest. Chúng ta dùng tên MyRepositoryTest.
Trước khi đi vào test Proto DataStore, cần khởi tạo nó. Nếu tìm tài liệu online, nó khá thưa thớt.
Khởi tạo Proto DataStore dùng global Context như sau (khi không phải test):
private val Context.myDataStore: DataStore<MyItem> by dataStore( fileName = DATA_STORE_FILE_NAME, serializer = MyItemSerializer )
Nhưng bạn không thể làm này trong class test, vì dù copy-paste code trên, bạn sẽ không thể truy cập đối tượng DataStore. Bạn có thể lấy application context thế này:
ApplicationProvider.getApplicationContext()
nhưng đối tượng myDataStore không thể truy cập qua nó.
Vậy làm sao?
Trong bài liên kết trên, có ví dụ tạo Preference DataStore dùng PreferenceDataStoreFactory.create method.
fun create( corruptionHandler: ReplaceFileCorruptionHandler<Preferences>? = null, migrations: List<DataMigration<Preferences>> = listOf(), scope: CoroutineScope = CoroutineScope(Dispatchers.IO + SupervisorJob()), produceFile: () -> File): DataStore<Preferences>
Nhưng vì chúng ta không dùng Preference DataStore, cách đó không dùng được. Cách sẽ dùng được là dùng DataStoreFactory.create method như sau:
fun <T : Any?> create( serializer: Serializer<T>, corruptionHandler: ReplaceFileCorruptionHandler<T>? = null, migrations: List<DataMigration<T>> = listOf(), scope: CoroutineScope = CoroutineScope(Dispatchers.IO + SupervisorJob()), produceFile: () -> File): DataStore<T>
Phương thức này có vài đối số (một số có giá trị mặc định), nhưng không cần truyền tất cả. Chúng ta sẽ truyền:
- Class serializer của chúng ta
- Lambda method tạo file cho Proto DataStore
dataStore = DataStoreFactory.create( produceFile = { testContext.dataStoreFile(TEST_DATA_STORE_FILE_NAME) }, serializer = MyItemSerializer )
Chúng ta lấy testContext bằng:
private val testContext: Context = ApplicationProvider.getApplicationContext()
Đã tạo Proto DataStore thành công, chuyển sang viết test. Nhớ rằng bạn có class repository nhận instance Proto DataStore làm dependency, nên sau khi tạo DataStore, cần tạo instance class repository.
private val repository = MyRepository(datastore)
Trước hết, tạo test kiểm tra trạng thái ban đầu của Proto DataStore. Proto DataStore expose một Flow chúng ta có thể dùng.
@OptIn(ExperimentalCoroutinesApi::class) @Test fun repository_testFetchInitialState() { runTest { testScope.launch { val dataStoreObject = repository.myFlow.first() // Chèn assert mong muốn từ Proto DataStore. VD: cờ có giá trị ban đầu false assert(dataStoreObject.myFlag == false) } } }
☝️ Bạn có thể nhận thấy sớm hơn, chúng ta dùng annotation OptIn ở đây. Vì (hiện tại) API chúng ta dùng là experimental và phải đánh dấu khi dùng.
Vì truy cập flow của DataStore, cần wrap trong testScope. TestScope tạo bằng:
@OptIn(ExperimentalCoroutinesApi::class) private val dispatcher = TestCoroutineDispatcher() @OptIn(ExperimentalCoroutinesApi::class) private val testScope = TestCoroutineScope(dispatcher)
Chạy và tận hưởng test Proto DataStore đầu tiên.
Vui được khoảng hai giây.
Làm điều có ý nghĩa hơn.
Tưởng tượng Proto DataStore có danh sách object bên trong và muốn test trạng thái khi thêm item vào.
@OptIn(ExperimentalCoroutinesApi::class) @Test fun repository_testAdditionOfItem() { runTest { testScope.launch { //1 val item: MyItem = MyItem.newBuilder().setItemId(UUID.randomUUID().toString()) .setItemDescription(TEST_ITEM_DESCRIPTION).build() //2 repository.updateItem(item) //3 val items = repository.myFlow.first().itemsList assert(items.size == 1) //4 assert(items[0].itemDescription.equals(TEST_ITEM_DESCRIPTION)) } } }
- Tạo item test dùng API exposed từ protobuff
- Thêm item vào Proto DataStore dùng method exposed trên class MyRepository
- Lấy danh sách item từ flow Proto DataStore expose
- Đảm bảo item tìm thấy trong Proto DataStore khớp item tạo trước
DataStore của bạn bị rò rỉ (Leak)
Nếu chạy các test trên cùng lúc, bạn sớm nhận lỗi runtime:
Có nhiều DataStore hoạt động cho cùng file: /data/user/0/com.example.app/files/datastore/dataStore_filename.pb. Bạn nên duy trì DataStore như singleton hoặc xác nhận không có hai DataStore hoạt động trên cùng file (bằng cách xác nhận scope bị cancel).
Vấn đề lớn. Chúng ta chỉ tạo một instance DataStore trong class test.
Đang xảy ra gì?
Vì không dùng property delegate tạo DataStore (tức Context.datastore), không đảm bảo đối tượng DataStore là singleton mỗi khi truy cập.
Để khắc phục, tôi tìm ra một cách: xóa và tái tạo DataStore cho mỗi test case. Để xóa DataStore:
@After fun cleanup() { File(testContext.filesDir, "datastore").deleteRecursively() }
và trước mỗi test, tạo lại:
@Before fun setup() { dataStore = DataStoreFactory.create( produceFile = { testContext.dataStoreFile(TEST_DATA_STORE_FILE_NAME) }, serializer = MyItemSerializer ) }
Để xem ví dụ đầy đủ, vào đây.
Trong bài này, tôi muốn chỉ ra khung khổ cách test Proto DataStore.
Mặc dù tôi đi qua hai test case, tùy DataStore và kiểu bạn cấu hình, có thể có nhiều test case và scenario hơn. Khối xây dựng đã có, bạn chỉ cần điều chỉnh cho nhu cầu.
Học lập trình miễn phí. Chương trình mở của freeCodeCamp đã giúp hơn 40.000 người có việc làm developer. Bắt đầu ngay