मैं अपने repository के लिए यूनिट टेस्ट लिखना चाहता हूं। repository की विधियां flow वापस आती हैं। addDiaryRate विधि सबसे पहले emit लोडिंग स्थिति फिर नेटवर्क से डेटा लौटाती है। मैं यह सत्यापित करना चाहता हूं कि addDiaryRate विधि लोड हो रही है फिर डेटा प्रतिक्रिया। मैं यह परीक्षण लिखता हूं लेकिन मेरा परीक्षण विफल रहा। त्रुटि कहती है कि अपेक्षित और वास्तविक समान नहीं हैं, जबकि वे समान हैं।

java.lang.AssertionError: अपेक्षित: है <डेटास्टेट (त्रुटि = शून्य, लोडिंग = लोड हो रहा है (isLoading = true), डेटा = शून्य)> लेकिन: था = घटना (सामग्री = दर प्रतिक्रिया (डेटा = दर मॉडल (आईडी = 1, प्रतीकपथ = प्रतीक पथ, दर = 3, बिंदु = 2.0, डायरी आईडी = 333, गिनती = 34)), हैबीनहैंडल = गलत))> अपेक्षित: है <डेटास्टेट ( त्रुटि = शून्य, लोड हो रहा है = लोड हो रहा है (इसलोडिंग = सत्य), डेटा = शून्य)> वास्तविक: <डेटास्टेट (त्रुटि = शून्य, लोडिंग = लोड हो रहा है (इसलोडिंग = गलत), डेटा = घटना (सामग्री = रेटरेस्पॉन्स (डेटा = रेटमोडेल (आईडी =) 1, सिंबलपाथ = सिंबल पाथ, रेट = 3, पॉइंट = 2.0, डायरी आईडी = 333, काउंट = 34)), हैबैनहैंडल = असत्य))>

मैं कोडलैब और Google नमूने के नमूना कोड का उपयोग करता हूं। यह MainRepository है:

   class MainRepositoryImp constructor(
    private val apiService: MainApiService,
    private val suggestionModelDao: SuggestionModelDao,
    private val userDao: UserDao,
    private val babyDao: BabyDao,
    private val diaryHotDao: DiaryHotDao,
    private val diaryUserDao: DiaryUserDao,
    private val hashTagModelDao: HashTagModelDao,
    private val diaryTopDao: DiaryTopDao,
    private val diaryResultSearchDao: DiaryResultSearchDao,
    private val rateModelDao: RateModelDao,
    private val medalDao: MedalDao,
    private val blogModelDao: BlogModelDao,
    private val seenDiaryDao: SeenDiaryDao,
    private val rateModelAppDao: RateModelAppDao,
    private val diarySavedDao: DiarySavedDao,
    private val diaryAnotherUserDao: DiaryAnotherUserDao,
    private val anotherUserInfoDao: AnotherUserInfoDao,
    private val followDao: FollowDao,
    private val suggestProductDao: SuggestProductDao,
    private val blogSuggestWithHashTagDao: BlogSuggestWithHashTagDao,
    private val suggestHashtagDao: SuggestHashtagDao,
    private val sessionManager: SessionManager
) : MainRepository {
 override fun addRateToDiary(rate: String, diaryId: String): Flow<DataState<RateResponse>> =
        flow {
            emit(DataState.loading(true))

            val apiResult = safeApiCall(
                sessionManager.isConnectedToTheInternet()
            ) {
                apiService.addRate(
                    diaryId,
                    AddRateRequest(rate),
                    sessionManager.cachedAccessToken.value ?: ""
                )
            }

            emit(
                object : ApiResponseHandler<RateResponse, RateResponse>(
                    response = apiResult
                ) {
                    override suspend fun handleSuccess(resultObj: RateResponse): DataState<RateResponse> {
                        safeCacheCall {
                            diaryHotDao.updateRateStateDiary(
                                resultObj.data.symbolPath ?: "",
                                diaryId,
                                resultObj.data.rate
                            )
                            var countRate = 0
                            var userId = 0
                            userDao.fetchUser()?.let {
                                countRate = it.countRates + 1
                                userId = it.id
                            }
                            userDao.updateCountRate(countRate, userId)
                        }
                        return DataState.data(resultObj)
                    }

                }.getResult()
            )
        }
}

यह मेरा टेस्ट क्लास है:

@ExperimentalCoroutinesApi
@RunWith(RobolectricTestRunner::class)
@InternalCoroutinesApi
class MainRepositoryTest
{
    private lateinit var repository: MainRepository
    private var apiService = FakeUnitTestApiService()

    private lateinit var suggestionModelDao: SuggestionModelDao
    private lateinit var userDao: UserDao
    private lateinit var babyDao: BabyDao
    private lateinit var diaryHotDao: DiaryHotDao
    private lateinit var diaryUserDao: DiaryUserDao
    private lateinit var hashTagModelDao: HashTagModelDao
    private lateinit var diaryTopDao: DiaryTopDao
    private lateinit var diaryResultSearchDao: DiaryResultSearchDao
    private lateinit var rateModelDao: RateModelDao
    private lateinit var medalDao: MedalDao
    private lateinit var blogModelDao: BlogModelDao
    private lateinit var seenDiaryDao: SeenDiaryDao
    private lateinit var rateModelAppDao: RateModelAppDao
    private lateinit var diarySavedDao: DiarySavedDao
    private lateinit var diaryAnotherUserDao: DiaryAnotherUserDao
    private lateinit var anotherUserInfoDao: AnotherUserInfoDao
    private lateinit var followDao: FollowDao
    private lateinit var suggestProductDao: SuggestProductDao
    private lateinit var blogSuggestWithHashTagDao: BlogSuggestWithHashTagDao
    private lateinit var suggestHashtagDao: SuggestHashtagDao


    private lateinit var sessionManager: SessionManager
    private lateinit var db: AppDatabase

    private lateinit var prefManager: PrefManager

    @Rule
    @JvmField
    val instantExecutorRule = InstantTaskExecutorRule()


    @ExperimentalCoroutinesApi
    @get:Rule
    var mainCoroutineRule = MainCoroutineRule()

    @Before
    fun init() {
      val app = ApplicationProvider.getApplicationContext<Application>()

        prefManager=PrefManager(app)
        db = Room.inMemoryDatabaseBuilder(
            app,
            AppDatabase::class.java
        ).allowMainThreadQueries().build()
        initDao()
        sessionManager = SessionManager(
            app,
            userDao,
            babyDao,
            diaryHotDao,
            diaryTopDao,
            diaryUserDao,
            hashTagModelDao,
            medalDao,
            suggestionModelDao,
            diaryResultSearchDao,
            rateModelDao,
            blogModelDao,
            seenDiaryDao,
            rateModelAppDao,
            diarySavedDao,
            diaryAnotherUserDao,
            anotherUserInfoDao,
            followDao,
            suggestProductDao,
            blogSuggestWithHashTagDao,
            suggestHashtagDao,
            prefManager
        )
  
        repository = MainRepositoryImp(
            apiService,
            suggestionModelDao,
            userDao,
            babyDao,
            diaryHotDao,
            diaryUserDao,
            hashTagModelDao,
            diaryTopDao,
            diaryResultSearchDao,
            rateModelDao,
            medalDao,
            blogModelDao,
            seenDiaryDao,
            rateModelAppDao,
            diarySavedDao,
            diaryAnotherUserDao,
            anotherUserInfoDao,
            followDao,
            suggestProductDao,
            blogSuggestWithHashTagDao,
            suggestHashtagDao,
            sessionManager
        )
    }

    private fun initDao() {
        suggestionModelDao = db.getSuggestionModelDao()
        userDao = db.getUserDao()
        babyDao = db.getBabyDao()
        diaryHotDao = db.getDiaryHotDao()
        diaryUserDao = db.getDiaryUserDao()
        hashTagModelDao = db.getHashTagModelDao()
        diaryTopDao = db.getDiaryTopDao()
        diaryResultSearchDao = db.getDiaryResultSearchDao()
        rateModelDao = db.getRateModelDao()
        medalDao = db.getMedalDao()
        blogModelDao = db.getBlogModelDao()
        seenDiaryDao = db.getSeenDiaryDao()
        rateModelAppDao = db.getRateModelAppDao()
        diarySavedDao = db.getDiarySavedDao()
        diaryAnotherUserDao = db.getDiaryAnotherUserDao()
        anotherUserInfoDao = db.getAnotherUserInfoDao()
        followDao = db.getFollowDao()
        suggestProductDao = db.getBlogProductDao()
        blogSuggestWithHashTagDao = db.getBlogSuggestWithHashTagDao()
        suggestHashtagDao = db.getBlogSuggestDao()
    }


    @Test
    fun addRateTest() = mainCoroutineRule.runBlockingTest{
        /** GIVEN  **/
        val response = RateResponse(
            RateModel(
                id = "1",
                symbolPath = "symbol path",
                rate = 3,
                point = 2f,
                diaryId = "333",
                count = "34"
            )
        )

        /** WHEN **/
        repository.addRateToDiary("2","333").collect{

            assertThat(it, `is`(DataState.loading<RateResponse>(true)))

            assertThat(it,`is`(DataState.data<RateResponse>(response)))
        }
    }
0
maryam 19 अक्टूबर 2020, 15:34

1 उत्तर

सबसे बढ़िया उत्तर

अंत में मुझे समाधान मिल गया। 1- मैं mainCoroutineRule.runBlockingTest के बजाय runBlocking का उपयोग करता हूं। 2- flow के सभी उत्सर्जित मान को सत्यापित करने के लिए, हम toList() विधि का उपयोग कर सकते हैं। यह मेरी नकली एपीआई सेवा है:

    open class FakeUnitTestApiService(
    var addRateImpl: suspend (
        id: String,
        addRateRequest: AddRateRequest,
        token: String
    ) -> GenericApiResponse<RateResponse> = notImplemented2()
) : MainApiService {
    companion object {
        private fun <T, R> notImplemented1(): suspend (t: T) -> R {
            return { t: T ->
                TODO("")
            }
        }

        private fun <T, R> notImplemented2(): suspend (t: T, s: T, l: T) -> R {
            return { t: T, s: T, l: T ->
                TODO("")
            }
        }
    }

    override suspend fun addRate(
        id: String,
        addRateRequest: AddRateRequest,
        token: String
    ): GenericApiResponse<RateResponse> = addRateImpl(id,addRateRequest,token)
}

और यह मेरा परीक्षण कार्य है:

@Test
fun addRateTest() = runBlocking{
    /** GIVEN  **/
    val response = RateResponse(
        RateModel(
            id = "1",
            symbolPath = "symbol path",
            rate = 3,
            point = 2f,
            diaryId = "333",
            count = "34"
        )
    )

    /** WHEN **/
    apiService.addRateImpl = { s: String, addRateRequest: AddRateRequest, s1: String ->
        GenericApiResponse.create(Response.success(response))
    }
    val list=repository.addRateToDiary("2","333").toList()

    /**THEN**/
    assertThat(list.first().loading.isLoading,`is`(true))
    assertThat(list.last().data?.peekContent(),`is`(response))
}
0
maryam 20 अक्टूबर 2020, 14:11