ktcheck is a test framework for Kotlin working on JUnit platform, with Given-When-Then style.
Use maven or Gradle.
pom.xml
<project>
<dependencies>
<dependency>
<group>run.ktcheck</group>
<artifactId>ktcheck</artifactId>
<version>v0.1.0</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.2</version>
</plugin>
<plugin>
<artifactId>maven-failsafe-plugin</artifactId>
<version>2.22.2</version>
</plugin>
</plugins>
</build>
</project>
build.gradle
dependencies {
testImplementation 'run.ktcheck:ktcheck:v0.1.0'
}
test {
useJUnitPlatform()
}
build.gradle.kts
dependencies {
testImplementation("run.ktcheck:ktcheck:v0.1.0")
}
test {
useJUnitPlatform()
}
After creating new Kotlin file, add ktcheck APIs.(of course you can import via IDE's auto completion.)
import run.ktcheck.KtCheck
import run.ktcheck.Given
object YourTest: KtCheck
- In a
Given
phrase, write description and function which returns a condition object. - In a
When
phrase, write description and function which takes the condition object and returns an action result. - In a
Then
phrase, write description and function which takes the condition object and the action result, and returns an assertion result.
object YourTest: KtCheck
by Given("TimeService with fixed clock", { TimeService(fixedClock) })
.When("get current time from TimeService#now", { timeService -> timeService.now() })
.Then("it should be fixed time", { _, instant -> instant shouldBe fixedInstant })
To create Assertion
object, use these functions.
run.ktcheck.assertion.NoDep.shouldBe
run.ktcheck.assertion.NoDep.shouldNotBe
run.ktcheck.assertion.NoDep.should
andrun.ktcheck.assertion.Matcher
If the condition object is not needed, a simple asserting function is available.
run.ktcheck.assertion.NoDep.expect
run.ktcheck.assertion.NoDep.expectNull
run.ktcheck.assertion.NoDep.expectNotNull
object YourTest: KtCheck
by Given("TimeService with fixed clock", { TimeService(fixedClock) })
.When("get current time from TimeService#now", { timeService -> timeService.now() })
.Then("it should be fixed time", expect(fixedInstant))
$ ./mvnw test
$ ./gradlew test
After creating new Kotlin file, add ktcheck APIs.(of course you can import via IDE's auto completion.)
import run.ktcheck.Given
- Create
KtCheck
object in main program fromGiven
class. - Run
KtCheck
usingrunStandalone()
function. - If test fails, it will throws
Unsuccessful
exception.
import java.time.Clock
import java.time.OffsetDateTime
import java.time.ZoneOffset
fun main() {
val fixedInstant = OffsetDateTime.of(2020, 1, 2, 15, 4, 5, 6, ZoneOffset.UTC).toInstant()
val fixedClock = Clock.fixed(fixedInstant, ZoneOffset.UTC)
val check = Given("TimeService with fixed clock") { TimeService(fixedClock) }
.When("get current time from TimeService#now") { timeService -> timeService.now() }
.Then("it should be fixed time") { _, instant -> instant shouldBe fixedInstant }
check.runStandalone()
}