Instantiate Dependency Injection Class using Kotlin in Unit Tests

Asked

Viewed 118 times

0

I’m trying to find a solution for how I can instantiate a class that uses dependency injection into unit testing using Kotlin and Junit.

I have a class that uses addiction injection:

class MinhaClasse @Inject constructor(val meuService: IMeuService, val outroService: IOutroService, val minhaFactory: IMinhaFactory): IMinhaClasse {
    ...
}

Where in my primary constructor I am injecting the interfaces where I will need.

I have my test file for this class:

class MeuServiceTest {
    private val meuService = mock(meuService::class.java)

    @Test
    fun meuMetodoTest() {
        val expectedResult = ...
        ...
        val result = runBlocking { meuService.meuMetodo(parametroDoMetodo) }
        assertEquals(expectedResult, result)
    }
}

I’m using runBlocking for this method is asynchronous.

As you can see I’m trying to mock my class but its return is null, I am using the Mockito library together with Junit for Kotlin described below:

    <dependency>
        <groupId>org.junit.jupiter</groupId>
        <artifactId>junit-jupiter-api</artifactId>
        <version>5.6.0-M1</version>
    </dependency>
    <dependency>
        <groupId>org.mockito</groupId>
        <artifactId>mockito-core</artifactId>
        <version>3.2.0</version>
        <scope>test</scope>
    </dependency>

The version of my Kotlin is 1.3.41 .

1 answer

0

After talking to more experienced devs I ended up adopting another library called Mockk that is able to mock interfaces and classes more easily!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.