Instantiate class with Dependency Injection using Kotlin in unit tests
I am trying to find a solution of how I can instantiate a class that uses dependency injection in unit tests using Kotlin and JUnit.
I have a class that uses dependency injection:
class MinhaClasse @Inject constructor(val meuService: IMeuService, val outroService: IOutroService, val minhaFactory: IMinhaFactory): IMinhaClasse {
...
}
Where in my primary constructor I'm injecting the interfaces from where I'm going to need it.
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 am using runblocking as this method is asynchronous.
How can they see I'm trying to mock my class but its return is null , I'm using the Mockito library next to 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 .
0
Author: Rafael de Mattos, 2020-02-13
1 answers
After talking to more experienced devs I ended up adopting another library called MockK which is able to perform mock interfaces and classes more easily!
0
Author: Rafael de Mattos, 2020-02-19 17:49:21