Best Kotest code snippet using io.kotest.matchers.optional.matchers.Optional.shouldBePresent
PostServiceTest.kt
Source:PostServiceTest.kt
1package com.github.njuro.jard.post2import com.github.njuro.jard.TestDataRepository3import com.github.njuro.jard.WithContainerDatabase4import com.github.njuro.jard.board5import com.github.njuro.jard.board.Board6import com.github.njuro.jard.post7import com.github.njuro.jard.thread8import com.github.njuro.jard.thread.Thread9import io.kotest.assertions.throwables.shouldThrow10import io.kotest.matchers.collections.shouldContainExactly11import io.kotest.matchers.nulls.shouldNotBeNull12import io.kotest.matchers.optional.shouldBePresent13import io.kotest.matchers.optional.shouldNotBePresent14import io.kotest.matchers.should15import io.kotest.matchers.shouldBe16import io.kotest.matchers.string.shouldContain17import org.junit.jupiter.api.BeforeEach18import org.junit.jupiter.api.Test19import org.springframework.beans.factory.annotation.Autowired20import org.springframework.boot.test.context.SpringBootTest21import org.springframework.transaction.annotation.Transactional22@SpringBootTest23@WithContainerDatabase24@Transactional25internal class PostServiceTest {26 @Autowired27 private lateinit var postService: PostService28 @Autowired29 private lateinit var postRepository: PostRepository30 @Autowired31 private lateinit var db: TestDataRepository32 private lateinit var board: Board33 private lateinit var thread: Thread34 @BeforeEach35 fun setUp() {36 board = db.insert(board(label = "r"))37 thread = db.insert(thread(board))38 }39 @Test40 fun `create new post`() {41 val post = post(thread, postNumber = 0L, body = "Test post\n")42 postService.savePost(post).should {43 it.id.shouldNotBeNull()44 it.postNumber shouldBe 1L45 it.body.shouldContain("<br/>")46 }47 }48 @Test49 fun `resolve post`() {50 val post = db.insert(post(thread, postNumber = 2L))51 postService.resolvePost(board.label, post.postNumber).postNumber shouldBe post.postNumber52 }53 @Test54 fun `don't resolve non-existing post`() {55 shouldThrow<PostNotFoundException> {56 postService.resolvePost(board.label, 0L)57 }58 }59 @Test60 fun `get latest replies for thread`() {61 (2L..8L).forEach { db.insert(post(thread, postNumber = it)) }62 postService.getLatestRepliesForThread(thread.id, thread.originalPost.id).map(Post::getPostNumber)63 .shouldContainExactly(4L, 5L, 6L, 7L, 8L)64 }65 @Test66 fun `delete single post`() {67 val reply = db.insert(post(thread, postNumber = 2L))68 db.select(reply).shouldBePresent()69 postService.deletePost(reply)70 db.select(reply).shouldNotBePresent()71 }72 @Test73 fun `delete multiple posts`() {74 val replies = (2L..5L).map { db.insert(post(thread, postNumber = it)) }75 postRepository.countByThreadId(thread.id) shouldBe 5L76 postService.deletePosts(replies)77 postRepository.countByThreadId(thread.id) shouldBe 1L78 }79}...
LivreAdapterTest.kt
Source:LivreAdapterTest.kt
1package fr.deroffal.bibliotheque.livre.adapter.repository2import fr.deroffal.bibliotheque.livre.domain.Livre3import io.kotest.matchers.collections.shouldContainExactly4import io.kotest.matchers.collections.shouldHaveSize5import io.kotest.matchers.optional.shouldBePresent6import io.kotest.matchers.shouldBe7import org.junit.jupiter.api.Test8import org.springframework.beans.factory.annotation.Autowired9import org.springframework.boot.test.autoconfigure.orm.jpa.AutoConfigureTestEntityManager10import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager11import org.springframework.boot.test.context.SpringBootTest12import org.springframework.test.context.TestPropertySource13import org.springframework.transaction.annotation.Transactional14import java.util.*15@TestPropertySource(locations = ["classpath:application-repositoryAdapterTest.properties"])16@AutoConfigureTestEntityManager17@SpringBootTest18@Transactional19internal class LivreAdapterTest {20 @Autowired21 private lateinit var livreAdapter: LivreAdapter22 @Autowired23 private lateinit var testEntityManager: TestEntityManager24 @Test25 fun `findById retourne le livre correspondant`() {26 //given:27 val entity = newLivreEntity("Harry Potter", "Fantastique")28 //when:29 val livreOptional = livreAdapter.findById(entity.id)30 //then:31 livreOptional.shouldBePresent()32 val livre = livreOptional.get()33 //and:34 livre.titre shouldBe "Harry Potter"35 livre.genre shouldBe "Fantastique"36 }37 @Test38 fun `findAllByGenre retourne tous les elements d'un genre donne`() {39 //given:40 newLivreEntity("Harry Potter", "Fantastique")41 newLivreEntity("Le Seigneur des Anneaux", "Fantastique")42 newLivreEntity("Dune", "Science-fiction")43 //when:44 val livres = livreAdapter.findAllByGenre("Fantastique")45 //then:46 livres shouldHaveSize 247 livres.map { it.titre }.sorted() shouldContainExactly listOf("Harry Potter", "Le Seigneur des Anneaux")48 }49 @Test50 fun `create retourne le livre cree`() {51 //given:52 val livreACree = Livre(UUID.randomUUID(), "Harry Potter", "Fantastique")53 //when:54 val livre = livreAdapter.create(livreACree)55 //then:56 livre.titre shouldBe "Harry Potter"57 livre.genre shouldBe "Fantastique"58 //and:59 val entity = testEntityManager.find(LivreEntity::class.java, livre.id)60 entity.id shouldBe livre.id61 entity.titre shouldBe "Harry Potter"62 entity.genre shouldBe "Fantastique"63 }64 private fun newLivreEntity(titre: String, genre: String) = testEntityManager.merge(LivreEntity(UUID.randomUUID(), titre, genre))65}...
OptionalMatchersTest.kt
Source:OptionalMatchersTest.kt
1package com.sksamuel.kotest.matchers.optional2import io.kotest.assertions.throwables.shouldThrow3import io.kotest.core.spec.style.ShouldSpec4import io.kotest.matchers.optional.beEmpty5import io.kotest.matchers.optional.bePresent6import io.kotest.matchers.optional.shouldBeEmpty7import io.kotest.matchers.optional.shouldBePresent8import io.kotest.matchers.optional.shouldNotBeEmpty9import io.kotest.matchers.optional.shouldNotBePresent10import io.kotest.matchers.should11import io.kotest.matchers.shouldBe12import io.kotest.matchers.shouldNot13import io.kotest.matchers.throwable.shouldHaveMessage14import java.util.Optional15class OptionalMatchersTest : ShouldSpec({16 context("Empty optional") {17 val optional = Optional.empty<Any>()18 should("Be empty") {19 optional.shouldBeEmpty()20 optional should beEmpty()21 }22 should("Not be present") {23 optional.shouldNotBePresent()24 optional shouldNot bePresent()25 }26 should("Fail to be notEmpty") {27 shouldThrow<AssertionError> { optional.shouldNotBeEmpty() }28 shouldThrow<AssertionError> { optional shouldNot beEmpty() }29 }30 should("Fail to be present") {31 shouldThrow<AssertionError> { optional.shouldBePresent() }32 shouldThrow<AssertionError> { optional should bePresent() }33 }34 }35 context("Present optional") {36 val optional = Optional.of("A")37 should("Be present") {38 optional.shouldBePresent()39 optional should bePresent()40 }41 42 should("Return the present value for usage in more assertions") {43 optional.shouldBePresent() shouldBe "A"44 } 45 should("Allow matchers with present value as a receiver") {46 optional shouldBePresent {47 this shouldBe "A"48 }49 }50 51 should("Allow matchers with present value as parameter") {52 optional shouldBePresent {53 it shouldBe "A"54 }55 }56 57 should("Execute code inside the receiver") {58 shouldThrow<RuntimeException> {59 optional shouldBePresent {60 throw RuntimeException("Ensuring the block is actually executed")61 }62 } shouldHaveMessage "Ensuring the block is actually executed"63 64 shouldThrow<AssertionError> {65 optional shouldBePresent {66 this shouldBe "B"67 }68 }69 }70 }71}) ...
UserServiceTest.kt
Source:UserServiceTest.kt
1package com.github.njuro.jard.user2import com.github.njuro.jard.TestDataRepository3import com.github.njuro.jard.WithContainerDatabase4import com.github.njuro.jard.WithMockJardUser5import com.github.njuro.jard.user6import io.kotest.matchers.booleans.shouldBeFalse7import io.kotest.matchers.booleans.shouldBeTrue8import io.kotest.matchers.collections.shouldHaveSize9import io.kotest.matchers.optional.shouldBeEmpty10import io.kotest.matchers.optional.shouldBePresent11import io.kotest.matchers.shouldBe12import org.junit.jupiter.api.Test13import org.springframework.beans.factory.annotation.Autowired14import org.springframework.boot.test.context.SpringBootTest15import org.springframework.transaction.annotation.Transactional16@SpringBootTest17@WithContainerDatabase18@Transactional19internal class UserServiceTest {20 @Autowired21 private lateinit var userService: UserService22 @Autowired23 private lateinit var db: TestDataRepository24 @Test25 fun `save user`() {26 val user = user(username = "Anonymous")27 userService.saveUser(user).username shouldBe user.username28 }29 @Test30 fun `get all users`() {31 repeat(3) { db.insert(user(username = "User $it", email = "user$it@email.com")) }32 userService.allUsers shouldHaveSize 333 }34 @Test35 fun `check that user exists`() {36 val user = db.insert(user(username = "Anonymous"))37 userService.doesUserExists(user.username).shouldBeTrue()38 userService.doesUserExists("other").shouldBeFalse()39 }40 @Test41 @WithMockJardUser(username = "Anonymous")42 fun `get current user`() {43 userService.currentUser.username shouldBe "Anonymous"44 }45 @Test46 @WithMockJardUser(UserAuthority.MANAGE_BOARDS, UserAuthority.MANAGE_USERS)47 fun `check if current user has authority`() {48 userService.hasCurrentUserAuthority(UserAuthority.MANAGE_BOARDS).shouldBeTrue()49 userService.hasCurrentUserAuthority(UserAuthority.MANAGE_USERS).shouldBeTrue()50 userService.hasCurrentUserAuthority(UserAuthority.MANAGE_BANS).shouldBeFalse()51 }52 @Test53 fun `delete user`() {54 val user = db.insert(user(username = "Anonymous"))55 db.select(user).shouldBePresent()56 userService.deleteUser(user)57 db.select(user).shouldBeEmpty()58 }59}...
BoardServiceTest.kt
Source:BoardServiceTest.kt
1package com.github.njuro.jard.board2import com.github.njuro.jard.TestDataRepository3import com.github.njuro.jard.WithContainerDatabase4import com.github.njuro.jard.board5import io.kotest.assertions.throwables.shouldThrow6import io.kotest.matchers.collections.shouldContainInOrder7import io.kotest.matchers.optional.shouldBeEmpty8import io.kotest.matchers.optional.shouldBePresent9import io.kotest.matchers.shouldBe10import io.kotest.matchers.shouldNotBe11import org.junit.jupiter.api.Test12import org.springframework.beans.factory.annotation.Autowired13import org.springframework.boot.test.context.SpringBootTest14import java.time.OffsetDateTime15@SpringBootTest16@WithContainerDatabase17internal class BoardServiceTest {18 @Autowired19 private lateinit var boardService: BoardService20 @Autowired21 private lateinit var db: TestDataRepository22 @Test23 fun `save board`() {24 val board = board("r", postCounter = 0L)25 val created = boardService.saveBoard(board)26 created.id shouldNotBe null27 created.postCounter shouldBe 1L28 }29 @Test30 fun `find all boards sorted by creation date`() {31 val baseDate = OffsetDateTime.now()32 val first = db.insert(board(label = "r", createdAt = baseDate))33 val second = db.insert(board(label = "sp", createdAt = baseDate.plusDays(1)))34 val third = db.insert(board(label = "fit", createdAt = baseDate.minusDays(1)))35 boardService.allBoards.shouldContainInOrder(third, first, second)36 }37 @Test38 fun `resolve board by label`() {39 val board = db.insert(board(label = "r"))40 boardService.resolveBoard(board.label) shouldBe board41 }42 @Test43 fun `don't resolve non-existing board`() {44 shouldThrow<BoardNotFoundException> {45 boardService.resolveBoard("xxx")46 }47 }48 @Test49 fun `register new post`() {50 val board = db.insert(board(label = "r", postCounter = 5L))51 boardService.registerNewPost(board) shouldBe board.postCounter52 db.select(board).shouldBePresent { it.postCounter shouldBe board.postCounter + 1 }53 }54 @Test55 fun `delete board`() {56 val board = db.insert(board(label = "r"))57 boardService.deleteBoard(board)58 db.select(board).shouldBeEmpty()59 }60}...
matchers.kt
Source:matchers.kt
1package io.kotest.matchers.optional2import io.kotest.matchers.Matcher3import io.kotest.matchers.MatcherResult4import io.kotest.matchers.should5import io.kotest.matchers.shouldNot6import java.util.Optional7/**8 * Asserts that a [Optional] is empty9 *10 * ```11 * Optional.empty().shouldBeEmpty() // Assertion passes12 *13 * Optional.of("A").shouldBeEmpty() // Assertion fails14 * ```15 */16fun <T> Optional<T>.shouldBeEmpty() = this should beEmpty()17/**18 * Asserts that a [Optional] is not empty19 *20 * ```21 * Optional.of("A").shouldNotBeEmpty() // Assertion passes22 *23 * Optional.empty().shouldNotBeEmpty() // Assertion fails24 * ```25 */26fun <T> Optional<T>.shouldNotBeEmpty() = this shouldNot beEmpty()27/**28 * Matcher to verify whether an [Optional] is empty or not29 */30fun <T> beEmpty() = object : Matcher<Optional<T>> {31 override fun test(value: Optional<T>) = MatcherResult(32 !value.isPresent,33 { "Expected optional to be empty, but instead was ${value.get()}" },34 { "Expected optional to not be empty, but was" }35 )36}37/**38 * Verifies if this [Optional] is present then execute [block] with it's value39 *40 * ```41 * val optional = Optional.of("A")42 *43 * optional shouldBePresent {44 * it shouldBe "A"45 * }46 *47 * ```48 */49infix fun <T> Optional<T>.shouldBePresent(block: T.(value: T) -> Unit): T {50 shouldBePresent()51 get().block(get())52 return get()53}54/**55 * Verifies if this [Optional] is present56 *57 * ```58 * val optional = Optional.of("A")59 *60 * optional.shouldBePresent()61 *62 * ```63 *64 * Further assertions can be made using the returned value65 *66 * ```67 * val optional = Optional.of("A")68 *69 * val present = optional.shouldBePresent()70 * present shouldBe "A"71 * ```72 *73 */74fun <T> Optional<T>.shouldBePresent(): T {75 this should bePresent()76 return get()77}78/**79 * Verifies t hat this Optional contains no value80 */81fun <T> Optional<T>.shouldNotBePresent() = this shouldNot bePresent()82/**83 * Matcher to verify whether a matcher contains a value or not84 */85fun <T> bePresent() = object : Matcher<Optional<T>> {86 override fun test(value: Optional<T>) = MatcherResult(87 value.isPresent,88 { "Expected optional to be present, but was empty instead" },89 { "Expected optional to not be present, but was ${value.get()}" }90 )91}...
BoardRepositoryTest.kt
Source:BoardRepositoryTest.kt
1package com.github.njuro.jard.board2import com.github.njuro.jard.WithContainerDatabase3import com.github.njuro.jard.board4import io.kotest.matchers.optional.shouldBeEmpty5import io.kotest.matchers.optional.shouldBePresent6import io.kotest.matchers.shouldBe7import org.junit.jupiter.api.Test8import org.springframework.beans.factory.annotation.Autowired9import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest10@DataJpaTest11@WithContainerDatabase12internal class BoardRepositoryTest {13 @Autowired14 private lateinit var boardRepository: BoardRepository15 @Test16 fun `find board by label`() {17 val expectedBoard = board(label = "fit")18 boardRepository.save(expectedBoard)19 val actualBoard = boardRepository.findByLabel(expectedBoard.label)20 actualBoard.shouldBePresent { it.label shouldBe expectedBoard.label }21 }22 @Test23 fun `don't find non-existing board by label`() {24 boardRepository.findByLabel("xxx").shouldBeEmpty()25 }26 @Test27 fun `retrieve post counter of board`() {28 val board = board(label = "r", postCounter = 10)29 boardRepository.save(board)30 boardRepository.getPostCounter(board.label) shouldBe board.postCounter31 }32 @Test33 fun `increase post counter of board`() {34 val board = board(label = "sp", postCounter = 15)35 boardRepository.save(board)36 boardRepository.increasePostNumber(board.label)37 boardRepository.findByLabel(board.label).shouldBePresent { it.postCounter shouldBe board.postCounter + 1 }38 }39}...
KoinModuleFactoryTest.kt
Source:KoinModuleFactoryTest.kt
1package dev.madetobuild.typedconfig.koin2import dev.madetobuild.typedconfig.runtime.source.MapSource3import dev.madetobuild.typedconfig.test.KoinConfig4import io.kotest.matchers.optional.shouldBePresent5import io.kotest.matchers.optional.shouldNotBePresent6import io.kotest.matchers.shouldBe7import org.junit.jupiter.api.Test8import org.junit.jupiter.api.extension.RegisterExtension9import org.koin.core.qualifier.named10import org.koin.test.KoinTest11import org.koin.test.inject12import org.koin.test.junit5.KoinTestExtension13import java.util.*14class KoinModuleFactoryTest : KoinTest {15 private val key by inject<Int>(named("integer"))16 private val nestedKey by inject<String>(named("nested.foo"))17 private val optionalKey by inject<Optional<Int>>(named("optionalKey"))18 private val optionalKey2 by inject<Optional<Int>>(named("optionalKey2"))19 @JvmField20 @RegisterExtension21 val koinTestExtension = KoinTestExtension.create {22 val input = mapOf(23 "integer" to 42,24 "nested.foo" to "bar",25 "optionalKey" to 1,26 // "optionalKey2" intentionally omitted27 )28 modules(KoinConfig(MapSource(input)).asKoinModule())29 }30 @Test31 fun topLevelKey() {32 key shouldBe 4233 }34 @Test35 fun nestedKey() {36 nestedKey shouldBe "bar"37 }38 @Test39 fun optionalAndPresent() {40 optionalKey shouldBePresent {41 it shouldBe 142 }43 }44 @Test45 fun optionalButAbsent() {46 optionalKey2.shouldNotBePresent()47 }48}...
Optional.shouldBePresent
Using AI Code Generation
1import io.kotest.matchers.optional.shouldBePresent2import io.kotest.matchers.optional.shouldBeAbsent3import io.kotest.matchers.optional.shouldBeEmpty4import io.kotest.matchers.optional.shouldBePresentAnd5import io.kotest.matchers.optional.shouldBePresentOr6import io.kotest.matchers.optional.shouldBePresentOrElse7import io.kotest.matchers.optional.shouldBePresentWith8import io.kotest.matchers.optional.shouldBePresentThat9import io.kotest.matchers.optional.shouldBePresentIf10import io.kotest.matchers.optional.shouldBePresentUnless11import io.kotest.matchers.optional.shouldBePresentWhen12import io.kotest.matchers.optional.shouldBePresentUnlessNull13import io.kotest.matchers.optional.shouldBePresentWhenNotNull14import io.kotest.matchers.optional.shouldBePresentIfNot15import io.kotest.match
Optional.shouldBePresent
Using AI Code Generation
1val optional : Optional < String > = Optional . empty ()2optional . shouldBePresent ()3val optional : Optional < String > = Optional . empty ()4optional . shouldBeAbsent ()5val optional : Optional < String > = Optional . of ( "Hello" )6optional . shouldBePresentAnd { it == "Hello" }7val optional : Optional < String > = Optional . empty ()8optional . shouldBePresentAnd { it == "Hello" }9val optional : Optional < String > = Optional . of ( "Hello" )10optional . shouldBePresentAnd { it == "Hello" }11val optional : Optional < String > = Optional . of ( "Hello" )12optional . shouldBePresentAnd { it == "Hello" }13val optional : Optional < String > = Optional . empty ()14optional . shouldBePresentAnd { it == "Hello" }15val optional : Optional < String > = Optional . empty ()16optional . shouldBePresentAnd { it == "Hello" }17val optional : Optional < String > = Optional . of ( "Hello" )18optional . shouldBePresentAnd { it == "Hello" }19val optional : Optional < String > = Optional . of ( "Hello" )20optional . shouldBePresentAnd { it == "Hello" }21val optional : Optional < String > = Optional . empty ()22optional . shouldBePresentAnd { it == "Hello" }
Optional.shouldBePresent
Using AI Code Generation
1"Optional should be present" {2val optional = Optional.of("Hello")3optional.shouldBePresent()4}5"Optional should be empty" {6val optional = Optional.empty()7optional.shouldBeEmpty()8}9}10}
Optional.shouldBePresent
Using AI Code Generation
1val optional: Optional<String> = Optional.of("Hello World")2val optional: Optional<String> = Optional.empty()3val optional: Optional<String> = Optional.of("Hello World")4val optional: Optional<String> = Optional.of("Hello World")5val optional: Optional<String> = Optional.empty()6val optional: Optional<String> = Optional.of("Hello World")7val optional: Optional<String> = Optional.empty()8val optional: Optional<String> = Optional.of("Hello World")9val optional: Optional<String> = Optional.empty()10val optional: Optional<String> = Optional.of("Hello World")
Optional.shouldBePresent
Using AI Code Generation
1val optional = Optional.of( "Kotest" )2optional.shouldBePresent()3optional.shouldBePresent( "Kotest" )4optional.shouldBePresent { it.length == 6 }5optional.shouldBePresent( "Kotest" ) { it.length == 6 }6val optional = Optional.empty()7optional.shouldBeAbsent()8optional.shouldBeAbsent( "Kotest" )9optional.shouldBeAbsent { it.length == 6 }10optional.shouldBeAbsent( "Kotest" ) { it.length == 6 }11Optional.shouldBePresent(expected: T)12Optional.shouldBePresent(expected: T, message: String)13Optional.shouldBePresent(expected: T, predicate: (T) -> Boolean)14Optional.shouldBePresent(expected: T, predicate: (T) -> Boolean, message: String)15Optional.shouldBePresent(message: String, predicate: (T) -> Boolean)16Optional.shouldBePresent(message: () -> String, predicate: (T) -> Boolean)17Optional.shouldBePresent(message: () -> String)18Optional.shouldBePresent(predicate: (T) -> Boolean, message: String)19Optional.shouldBePresent(predicate: (T) -> Boolean)20Optional.shouldBePresent(predicate: (T) -> Boolean, message: () -> String)21Optional.shouldBePresent(message: () -> String, predicate: (T) -> Boolean)22Optional.shouldBePresent(message: String, predicate: (T) -> Boolean)23Optional.shouldBePresent(message: String)24Optional.shouldBePresent()25Optional.shouldBePresent(predicate: (T) -> Boolean, message: () -> String)26Optional.shouldBePresent(message: () -> String)27Optional.shouldBePresent(expected: T, message: () -> String)28Optional.shouldBePresent(expected: T, predicate: (T) -> Boolean, message: () -> String)29Optional.shouldBePresent(expected: T, predicate: (T) -> Boolean, message: String)30Optional.shouldBePresent(expected: T, message: () -> String)31Optional.shouldBePresent(expected: T, predicate: (T) -> Boolean, message: () -> String)32Optional.shouldBePresent(expected: T, predicate:
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!