mardi 28 juillet 2020

MockK - cannot mock same function twice

I am trying to test the getTopicNames function (below) in two scenarios: If it succeeds and if it does not succeed.

fun getTopicNames(): Either<Exception, Set<String>> =
    try {
        adminClient.listTopics()
            .names()
            .get()
            .right()
    } catch (exception: ExecutionException) {
        exception.left()
    }

This is the test class in which I am doing those two scenarios. If I run each test individually, they both suceed. If I run the entire class the second to execute fails because for some reason the previous mock on adminClient.listTopics() is being retained.

These are the versions for everything involved:

  • kotlin: 1.3.72

  • koin: 2.1.6

  • junit: 5.6.1

  • mockk: 1.10.0

class TopicOperationsTest {

    @BeforeEach
    fun start() {
        val testModule = module(createdAtStart = true) {
            single { mockk<AdminClient>() }
        }
        startKoin { modules(testModule) }
    }

    @AfterEach
    fun stop() {
        stopKoin()
    }

    @Test
    fun `getTopicNames() returns a Right with the topics names`() {
        val adminClient = get(AdminClient::class.java)

        val listOfTopicsToReturn = mockk<ListTopicsResult>()
        val expectedTopics = setOf("Topic1", "Topic2", "Topic3")

        every { adminClient.listTopics() } returns listOfTopicsToReturn
        every { listOfTopicsToReturn.names() } returns KafkaFuture.completedFuture(expectedTopics)

        println("listOfTopicsToReturn.names(): " + listOfTopicsToReturn.names())
        println("adminClient.listTopics(): " + adminClient.listTopics())
        println("getTopicNames(): " + getTopicNames())

        assertThat(getTopicNames().getOrElse { emptySet() }, `is`(expectedTopics))
    }

    @Test
    fun `getTopicNames() returns a Left if failing to get topic names`() {
        val adminClient = get(AdminClient::class.java)

        every { adminClient.listTopics() } throws ExecutionException("Some Failure", Exception())

        assertThat(getTopicNames(), IsInstanceOf(Either.Left::class.java))
    }
}

This is the error I get, caused by the fact that the test that verifies the failure is the first to run:

java.lang.AssertionError: 
Expected: is <[Topic1, Topic2, Topic3]>
     but: was <[]>
Expected :is <[Topic1, Topic2, Topic3]>
Actual   :<[]>
<Click to see difference>

Already tried clearAllMocks() on the BeforeEach method but it does not solve my problem as I just start getting:

io.mockk.MockKException: no answer found for: AdminClient(#1).listTopics()

Aucun commentaire:

Enregistrer un commentaire