jeudi 18 juin 2020

Testing periodic work, WorkInfo sometimes result `Running` state

I'm following this link to write tests for android Worker, wherein I assert the WorkState to be Enqueued, but it fails intermittently with

java.lang.AssertionError: 
    Expected: is <ENQUEUED>
         but: was <RUNNING>

I can see the logs for the tests which seems to suggest that the work has already been finished with Success. so the assertion should've worked right?

D/WM-WorkConstraintsTrack: Constraints met for ef9d4cf7-a154-40a5-836b-0f168adb6898
D/WM-WorkConstraintsTrack: Constraints met for ef9d4cf7-a154-40a5-836b-0f168adb6898
D/WM-ConstraintTrkngWrkr: Constraints met for delegate <package_name>.<worker_class>
D/WM-Processor: Work ef9d4cf7-a154-40a5-836b-0f168adb6898 is already enqueued for processing
D/WM-WorkerWrapper: androidx.work.impl.workers.ConstraintTrackingWorker returned a Success {mOutputData=Data {}} result.
I/WM-WorkerWrapper: Worker result SUCCESS for Work [ id=ef9d4cf7-a154-40a5-836b-0f168adb6898, tags={ e8c3f53728904635964412c75923d217, <package_name>.<worker_class> } ]
D/WM-Processor: Processor ef9d4cf7-a154-40a5-836b-0f168adb6898 executed; reschedule = false
E/TestRunner: failed: testPeriodicFormSubmission_WithSuccess(<package_name>.<worker_class>)
E/TestRunner: ----- begin exception -----
E/TestRunner: java.lang.AssertionError: 
    Expected: is <ENQUEUED>
         but: was <RUNNING>

My test function is really simple,

@Test
    fun testPeriodicFormSubmission_WithSuccess() {
        // Mock the result
        every { submissionHelper.uploadForms() } returns UploadResult.FULL_SUCCESS
        // Enqueue the periodic work request.
        val operation = workManager.enqueue(request)

        // Tell the testing framework that the constraints are met.
        testDriver.setAllConstraintsMet(request.id)
        testDriver.setPeriodDelayMet(request.id)

        // Wait for result
        operation.result.get()

        // Get work info and assert
        val workInfo = workManager.getWorkInfoById(request.id).get()
        verify(exactly = 1) { submissionHelper.uploadForms() }
        Assert.assertThat(workInfo.state, CoreMatchers.`is`(WorkInfo.State.ENQUEUED))
    }

I'm not sure if assertion is a good way to test this flow or are there better alternatives to verify the worker states?

Aucun commentaire:

Enregistrer un commentaire