Skip to content

'Mockito.RETURNS_SELF' does not work for a supendable builder methods #550

@m-koops

Description

@m-koops

When stubbing a suspendable builder method to return the mock itselfs, this works fine for sync methods, but fails for suspend functions.

The failure can be demonstrated by this simple test:

package test

import com.nhaarman.expect.expect
import kotlinx.coroutines.test.runTest
import org.junit.Test
import org.mockito.Mockito
import org.mockito.kotlin.mock

interface Builder {
    suspend fun builderMethod(): Builder
}

class SimpleTest {
    @Test
    fun `should mock builder method returning mock itself via defaultAnswer`() = runTest {
        /* Given */
        val mock = mock<Builder>(defaultAnswer = Mockito.RETURNS_SELF)

        /* When */
        val result = mock.builderMethod()

        /* Then */
        expect(result).toBeTheSameAs(mock)
    }

    @Test
    fun `should mock builder method returning mock itself via answer`() = runTest {
        /* Given */
        val mock = mock<Builder> {
            onBlocking { builderMethod() } doAnswer Mockito.RETURNS_SELF
        }

        /* When */
        val result = mock.builderMethod()

        /* Then */
        expect(result).toBeTheSameAs(mock)
    }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions