mockito / mockito-kotlin

Using Mockito with Kotlin
MIT License
3.1k stars 200 forks source link

argThat with File treats the parameter file as the test itself and fails #390

Open babramovitch opened 3 years ago

babramovitch commented 3 years ago

I'm writing a test where I want to validate that the path of a file i'm about to delete is correct.

    @Test
    fun `clearPurgeDataAndExpiredDrafts clears PugeMedia`() {
        val file: File = mock()

        whenever(context.filesDir).thenReturn(file)
        whenever(file.absolutePath).thenReturn("/path/")

        mediaCleaner.clearPurgeDataAndExpiredDrafts()

        verify(fileDeleter).delete(argThat {
            this.absolutePath == "/path/purge_media"
        })
    }

When the test runs instead of passing like it should, it returns the following error

Wanted but not invoked: fileDeleter.delete( <Purge data and expired drafts clears purge media$$inlined$arg that$ 1> ); -> at com.FileDeleter.delete(FileDeleter.kt:7)

However, there was exactly 1 interaction with this mock: fileDeleter.deleteRecursively( /path/purge_media );

I can get around this by using an argument captor instead

   @Test
    fun `clearPurgeDataAndExpiredDrafts clears PugeMedia`() {
        val file: File = mock()

        whenever(context.filesDir).thenReturn(file)
        whenever(file.absolutePath).thenReturn("/path/")

        val captor = argumentCaptor<File>()

        mediaCleaner.clearPurgeDataAndExpiredDrafts()

        verify(fileDeleter).deleteRecursively(captor.capture())

        assertEquals("/path/purge_media", captor.firstValue.absolutePath)
    }

I verified it's still in the latest versions of Mockito and Mockito Kotlin, but it was happening as far back as the 2.0 betas which I hadn't upgraded from.

Mockito 3.5.15 Mockito Kotlin 2.2.0