Unit test in Kotlin con JUnit 5
Ho specificato la versione 5 di JUnit perchè da quello che ho capito presenta delle differenze con la 4.
A partire anche dal repo da cui installare la libreria.
In questo articolo vediamo come usarla in Kotlin.
Se usate Maven:
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>5.10.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>5.10.0</version>
<scope>test</scope>
</dependency>
A questo punto creiamo una classe che svolge delle operazioni, che sarnno quelle da testare:
package org.example
class Calculator {
fun add(a: Int, b: Int): Int {
return a + b
}
}
Il package è org.example, tenetelo a mente.
Quindi abbiamo questo albero: src -> main -> java -> org.example -> Calculator.java.
Adesso ne dobbiamo creare uno simile per il test: src -> test -> java -> org.example -> CalculatorTest.java.
Dove la classe CalculatorTest è questa:
import org.example.Calculator
import org.junit.jupiter.api.Assertions
import org.junit.jupiter.api.DisplayName
import org.junit.jupiter.api.Test
class CalculatorTest {
private val calculator = Calculator()
@Test
@DisplayName("Test della somma di due numeri")
fun testAdd() {
Assertions.assertEquals(5, calculator.add(2, 3), "2 + 3 dovrebbe essere uguale a 5")
}
}
Adesso dovete lanciare il test.
Questo dipende da cosa volete usare.
Se volete usare Maven:
mvn test
Se avete IntelliJ potete creare una configurazione di tipo JUnit ed usare quella; con altri IDE non so.
Enjoy!
kotlin maven junit
Commentami!