How to use Throwable.shouldHaveCause method of io.kotest.matchers.throwable.matchers class

Best Kotest code snippet using io.kotest.matchers.throwable.matchers.Throwable.shouldHaveCause

matchers.kt

Source:matchers.kt Github

copy

Full Screen

1package tutorial.kotest2import io.kotest.assertions.throwables.shouldThrow3import io.kotest.assertions.throwables.shouldThrowAny4import io.kotest.assertions.throwables.shouldThrowExactly5import io.kotest.core.spec.style.DescribeSpec6import io.kotest.core.test.AssertionMode7import io.kotest.matchers.booleans.shouldBeTrue8import io.kotest.matchers.collections.shouldBeIn9import io.kotest.matchers.collections.shouldBeOneOf10import io.kotest.matchers.collections.shouldBeSameSizeAs11import io.kotest.matchers.collections.shouldBeSingleton12import io.kotest.matchers.collections.shouldBeSmallerThan13import io.kotest.matchers.collections.shouldBeSorted14import io.kotest.matchers.collections.shouldBeUnique15import io.kotest.matchers.collections.shouldContain16import io.kotest.matchers.collections.shouldContainAll17import io.kotest.matchers.collections.shouldContainAnyOf18import io.kotest.matchers.collections.shouldContainDuplicates19import io.kotest.matchers.collections.shouldContainExactly20import io.kotest.matchers.collections.shouldContainExactlyInAnyOrder21import io.kotest.matchers.collections.shouldContainInOrder22import io.kotest.matchers.collections.shouldContainNull23import io.kotest.matchers.collections.shouldEndWith24import io.kotest.matchers.collections.shouldHaveAtLeastSize25import io.kotest.matchers.collections.shouldHaveLowerBound26import io.kotest.matchers.collections.shouldHaveSingleElement27import io.kotest.matchers.collections.shouldHaveSize28import io.kotest.matchers.collections.shouldHaveUpperBound29import io.kotest.matchers.collections.shouldNotContainAnyOf30import io.kotest.matchers.collections.shouldNotHaveElementAt31import io.kotest.matchers.collections.shouldStartWith32import io.kotest.matchers.comparables.shouldBeEqualComparingTo33import io.kotest.matchers.comparables.shouldBeLessThanOrEqualTo34import io.kotest.matchers.date.shouldBeToday35import io.kotest.matchers.date.shouldHaveSameHoursAs36import io.kotest.matchers.doubles.Percentage37import io.kotest.matchers.doubles.beNaN38import io.kotest.matchers.doubles.plusOrMinus39import io.kotest.matchers.doubles.shouldBeNaN40import io.kotest.matchers.doubles.shouldNotBeNaN41import io.kotest.matchers.equality.shouldBeEqualToComparingFields42import io.kotest.matchers.equality.shouldBeEqualToComparingFieldsExcept43import io.kotest.matchers.equality.shouldBeEqualToIgnoringFields44import io.kotest.matchers.equality.shouldBeEqualToUsingFields45import io.kotest.matchers.file.shouldBeADirectory46import io.kotest.matchers.file.shouldBeAbsolute47import io.kotest.matchers.file.shouldExist48import io.kotest.matchers.file.shouldNotBeEmpty49import io.kotest.matchers.ints.beOdd50import io.kotest.matchers.ints.shouldBeBetween51import io.kotest.matchers.ints.shouldBeInRange52import io.kotest.matchers.ints.shouldBeLessThan53import io.kotest.matchers.ints.shouldBeLessThanOrEqual54import io.kotest.matchers.ints.shouldBeOdd55import io.kotest.matchers.ints.shouldBePositive56import io.kotest.matchers.ints.shouldBeZero57import io.kotest.matchers.iterator.shouldBeEmpty58import io.kotest.matchers.iterator.shouldHaveNext59import io.kotest.matchers.maps.shouldBeEmpty60import io.kotest.matchers.maps.shouldContain61import io.kotest.matchers.maps.shouldContainAll62import io.kotest.matchers.maps.shouldContainExactly63import io.kotest.matchers.maps.shouldContainKey64import io.kotest.matchers.nulls.shouldBeNull65import io.kotest.matchers.nulls.shouldNotBeNull66import io.kotest.matchers.shouldBe67import io.kotest.matchers.shouldNot68import io.kotest.matchers.shouldNotBe69import io.kotest.matchers.string.beEmpty70import io.kotest.matchers.string.shouldBeBlank71import io.kotest.matchers.string.shouldBeEmpty72import io.kotest.matchers.string.shouldBeEqualIgnoringCase73import io.kotest.matchers.string.shouldBeInteger74import io.kotest.matchers.string.shouldBeLowerCase75import io.kotest.matchers.string.shouldBeUpperCase76import io.kotest.matchers.string.shouldContain77import io.kotest.matchers.string.shouldContainADigit78import io.kotest.matchers.string.shouldContainIgnoringCase79import io.kotest.matchers.string.shouldContainOnlyDigits80import io.kotest.matchers.string.shouldContainOnlyOnce81import io.kotest.matchers.string.shouldEndWith82import io.kotest.matchers.string.shouldHaveLength83import io.kotest.matchers.string.shouldHaveLineCount84import io.kotest.matchers.string.shouldHaveMaxLength85import io.kotest.matchers.string.shouldHaveMinLength86import io.kotest.matchers.string.shouldHaveSameLengthAs87import io.kotest.matchers.string.shouldMatch88import io.kotest.matchers.string.shouldNotBeEmpty89import io.kotest.matchers.string.shouldStartWith90import io.kotest.matchers.throwable.shouldHaveCause91import io.kotest.matchers.throwable.shouldHaveCauseInstanceOf92import io.kotest.matchers.throwable.shouldHaveCauseOfType93import io.kotest.matchers.throwable.shouldHaveMessage94import io.kotest.matchers.types.shouldBeInstanceOf95import io.kotest.matchers.types.shouldBeSameInstanceAs96import io.kotest.matchers.types.shouldBeTypeOf97import io.kotest.matchers.uri.shouldHaveHost98import io.kotest.matchers.uri.shouldHavePort99import io.kotest.matchers.uri.shouldHaveScheme100import java.io.File101import java.net.URI102import java.time.LocalDate103import java.time.LocalTime104// https://kotest.io/docs/assertions/core-matchers.html105class MatchersTest : DescribeSpec({106 describe("general") {107 it("basics") {108 (1 == 1).shouldBeTrue()109 (2 + 2) shouldBe 4110 val foo: Any = "foobar"111 foo.shouldBeTypeOf<String>() shouldContain "fo"112 "".shouldBeEmpty()113 "x".shouldNot(beEmpty()) // manually negate114 "x".shouldNotBeEmpty() // reusable115 URI("https://tba") shouldHaveHost "tba"116 URI("https://tba:81") shouldHavePort 81117 URI("https://tba") shouldHaveScheme "https"118 File("/").apply {119 shouldExist()120 shouldBeADirectory()121 shouldBeAbsolute()122 shouldNotBeEmpty()123 }124 // executable, hidden, readable, smaller, writeable, containFile, extension, path, ...125 LocalDate.now().shouldBeToday()126 // before/after, within, same, between, have year/month/day/hour/...127 LocalTime.now().shouldHaveSameHoursAs(LocalTime.now())128 // before/after/between, sameMinute/Seconds/Nanos129 }130 it("numbers") {131 1 shouldBeLessThan 2132 1 shouldBeLessThanOrEqual 1 // Int-based; returns this133 1 shouldBeLessThanOrEqualTo 1 // Comparble-based; void134 1 shouldBeEqualComparingTo 1 // Comparable-based135 1.shouldBeBetween(0, 2)136 1 shouldBeInRange 0..2137 0.shouldBeZero()138 1.shouldBePositive()139 1.shouldBeOdd()140 (1.2).shouldBe(1.20001.plusOrMinus(Percentage(20.0)))141 (1.2).shouldNotBeNaN()142 }143 it("strings") {144 // generic: "abc" shouldBe "abc"145 "aBc" shouldBeEqualIgnoringCase "abc"146 "".shouldBeEmpty()147 " ".shouldBeBlank() // empty or whitespace148 "abc" shouldContain ("b")149 "aBc" shouldContainIgnoringCase "bc"150 "x-a-x" shouldContain """\-[a-z]\-""".toRegex()151 "-a-" shouldMatch """\-[a-z]\-""".toRegex()152 "abc" shouldStartWith ("a")153 "abc" shouldEndWith ("c")154 "ab aa" shouldContainOnlyOnce "aa"155 "abc".shouldBeLowerCase()156 "ABC".shouldBeUpperCase()157 "abc" shouldHaveLength 3158 "a\nb" shouldHaveLineCount 2159 "ab" shouldHaveMinLength 1 shouldHaveMaxLength 3160 "abc" shouldHaveSameLengthAs "foo"161 "1".shouldBeInteger()162 "12".shouldContainOnlyDigits()163 "abc1".shouldContainADigit() // at least one164 }165 it("types") {166 @Connotation167 open class SuperType()168 class SubType : SuperType()169 val sameRef = SuperType()170 sameRef.shouldBeSameInstanceAs(sameRef)171 val superType: SuperType = SubType()172 superType.shouldBeTypeOf<SubType>() // exact runtime match (SuperType won't work!)173 superType.shouldBeInstanceOf<SuperType>() // T or below174// SubType().shouldHaveAnnotation(Connotation::class)175 val nullable: String? = null176 nullable.shouldBeNull()177 }178 it("collections") {179 emptyList<Int>().iterator().shouldBeEmpty()180 listOf(1).iterator().shouldHaveNext()181 listOf(1, 2) shouldContain 1 // at least182 listOf(1, 2) shouldContainExactly listOf(1, 2) // in-order; not more183 listOf(1, 2) shouldContainExactlyInAnyOrder listOf(2, 1) // out-order; not more184 listOf(0, 3, 0, 4, 0).shouldContainInOrder(3, 4) // possible items in between185 listOf(1) shouldNotContainAnyOf listOf(2, 3) // black list186 listOf(1, 2, 3) shouldContainAll listOf(3, 2) // out-order; more187 listOf(1, 2, 3).shouldBeUnique() // no duplicates188 listOf(1, 2, 2).shouldContainDuplicates() // at least one duplicate189 listOf(1, 2).shouldNotHaveElementAt(1, 3)190 listOf(1, 2) shouldStartWith 1191 listOf(1, 2) shouldEndWith 2192 listOf(1, 2) shouldContainAnyOf listOf(2, 3)193 val x = SomeType(1)194 x shouldBeOneOf listOf(x) // by reference/instance195 x shouldBeIn listOf(SomeType(1)) // by equality/structural196 listOf(1, 2, null).shouldContainNull()197 listOf(1) shouldHaveSize 1198 listOf(1).shouldBeSingleton() // size == 1199 listOf(1).shouldBeSingleton {200 it.shouldBeOdd()201 }202 listOf(1).shouldHaveSingleElement {203 beOdd().test(it).passed() // have to return a boolean here :-/204 }205 listOf(2, 3) shouldHaveLowerBound 1 shouldHaveUpperBound 4206 listOf(1) shouldBeSmallerThan listOf(1, 2)207 listOf(1) shouldBeSameSizeAs listOf(2)208 listOf(1, 2) shouldHaveAtLeastSize 1209 listOf(1, 2).shouldBeSorted()210 mapOf(1 to "a").shouldContain(1, "a") // at least this211 mapOf(1 to "a") shouldContainAll mapOf(1 to "a") // at least those212 mapOf(1 to "a") shouldContainExactly mapOf(1 to "a") // not more213 mapOf(1 to "a") shouldContainKey 1214 emptyMap<Any, Any>().shouldBeEmpty()215 }216 it("exceptions") {217 class SubException() : Exception()218 Exception("a") shouldHaveMessage "a" // same (not contains!)219 Exception("abc").message shouldContain "b"220 Exception("", Exception()).shouldHaveCause()221 Exception("symptom", Exception("cause")).shouldHaveCause {222 it.message shouldBe "cause"223 }224 Exception("", SubException()).shouldHaveCauseInstanceOf<Exception>() // T or subclass225 Exception("", SubException()).shouldHaveCauseOfType<SubException>() // exactly T226 shouldThrow<Exception> { // type or subtype227 throw SubException()228 }229 shouldThrowExactly<Exception> { // exactly that type (no subtype!)230 throw Exception()231 }232 shouldThrowAny { // don't care which233 throw Exception()234 }235 }236 }237 describe("advanced") {238 it("selective matcheres") {239 data class Foo(val p1: Int, val p2: Int)240 val foo1 = Foo(1, 1)241 val foo2 = Foo(1, 2)242 foo1.shouldBeEqualToUsingFields(foo2, Foo::p1)243 foo1.shouldBeEqualToIgnoringFields(foo2, Foo::p2)244 class Bar(val p1: Int, val p2: Int) // not a data class! no equals.245 val bar1a = Bar(1, 1)246 val bar1b = Bar(1, 1)247 bar1a shouldNotBe bar1b248 bar1a shouldBeEqualToComparingFields bar1b // "fake equals" (ignoring private properties)249 bar1a.shouldBeEqualToComparingFields(bar1b, false) // explicitly also check private props250 val bar2 = Bar(1, 2)251 bar1a.shouldBeEqualToComparingFieldsExcept(bar2, Bar::p2)252 }253 }254 // channels255 // concurrent, futures256 // result, optional257 // threads258 // reflection259 // statistic, regex260})261private data class SomeType(val value: Int = 1)262private annotation class Connotation...

Full Screen

Full Screen

ThrowableMatchersTest.kt

Source:ThrowableMatchersTest.kt Github

copy

Full Screen

1package com.sksamuel.kotest.matchers.throwable2import io.kotest.assertions.throwables.shouldThrow3import io.kotest.assertions.throwables.shouldThrowAny4import io.kotest.assertions.throwables.shouldThrowExactly5import io.kotest.assertions.throwables.shouldThrowWithMessage6import io.kotest.core.spec.style.FreeSpec7import io.kotest.matchers.throwable.shouldHaveCause8import io.kotest.matchers.throwable.shouldHaveCauseInstanceOf9import io.kotest.matchers.throwable.shouldHaveCauseOfType10import io.kotest.matchers.throwable.shouldHaveMessage11import io.kotest.matchers.throwable.shouldNotHaveCause12import io.kotest.matchers.throwable.shouldNotHaveCauseInstanceOf13import io.kotest.matchers.throwable.shouldNotHaveCauseOfType14import io.kotest.matchers.throwable.shouldNotHaveMessage15import java.io.FileNotFoundException16import java.io.IOException17class ThrowableMatchersTest : FreeSpec() {18 init {19 "shouldThrowAny" - {20 "shouldHaveMessage" {21 shouldThrowAny { throw FileNotFoundException("this_file.txt not found") } shouldHaveMessage "this_file.txt not found"22 shouldThrowAny { throw TestException() } shouldHaveMessage "This is a test exception"23 shouldThrowAny { throw CompleteTestException() } shouldHaveMessage "This is a complete test exception"24 }25 "shouldNotHaveMessage" {26 shouldThrowAny { throw FileNotFoundException("this_file.txt not found") } shouldNotHaveMessage "random message"27 shouldThrowAny { throw TestException() } shouldNotHaveMessage "This is a complete test exception"28 shouldThrowAny { throw CompleteTestException() } shouldNotHaveMessage "This is a test exception"29 }30 "shouldHaveCause" {31 shouldThrowAny { throw CompleteTestException() }.shouldHaveCause()32 shouldThrowAny { throw CompleteTestException() }.shouldHaveCause {33 it shouldHaveMessage "file.txt not found"34 }35 }36 "shouldNotHaveCause" {37 shouldThrowAny { throw TestException() }.shouldNotHaveCause()38 shouldThrowAny { throw FileNotFoundException("this_file.txt not found") }.shouldNotHaveCause()39 }40 "shouldHaveCauseInstanceOf" {41 shouldThrowAny { throw CompleteTestException() }.shouldHaveCauseInstanceOf<FileNotFoundException>()42 shouldThrowAny { throw CompleteTestException() }.shouldHaveCauseInstanceOf<IOException>()43 }44 "shouldNotHaveCauseInstanceOf" {45 shouldThrowAny { throw CompleteTestException() }.shouldNotHaveCauseInstanceOf<TestException>()46 }47 "shouldHaveCauseOfType" {48 shouldThrowAny { throw CompleteTestException() }.shouldHaveCauseOfType<FileNotFoundException>()49 }50 "shouldNotHaveCauseOfType" {51 shouldThrowAny { throw CompleteTestException() }.shouldNotHaveCauseOfType<IOException>()52 }53 }54 "shouldThrow" - {55 "shouldHaveMessage" {56 shouldThrow<IOException> { throw FileNotFoundException("this_file.txt not found") } shouldHaveMessage "this_file.txt not found"57 shouldThrow<TestException> { throw TestException() } shouldHaveMessage "This is a test exception"58 shouldThrow<CompleteTestException> { throw CompleteTestException() } shouldHaveMessage "This is a complete test exception"59 shouldThrow<AssertionError> { TestException() shouldHaveMessage "foo" }60 .shouldHaveMessage(61 """Throwable should have message:62"foo"63Actual was:64"This is a test exception"65expected:<"foo"> but was:<"This is a test exception">"""66 )67 }68 "shouldNotHaveMessage" {69 shouldThrow<IOException> { throw FileNotFoundException("this_file.txt not found") } shouldNotHaveMessage "random message"70 shouldThrow<TestException> { throw TestException() } shouldNotHaveMessage "This is a complete test exception"71 shouldThrow<CompleteTestException> { throw CompleteTestException() } shouldNotHaveMessage "This is a test exception"72 shouldThrow<AssertionError> { TestException() shouldNotHaveMessage "This is a test exception" }73 .shouldHaveMessage("Throwable should not have message:\n\"This is a test exception\"")74 }75 "shouldHaveCause" {76 shouldThrow<CompleteTestException> { throw CompleteTestException() }.shouldHaveCause()77 shouldThrow<CompleteTestException> { throw CompleteTestException() }.shouldHaveCause {78 it shouldHaveMessage "file.txt not found"79 }80 shouldThrow<AssertionError> { TestException().shouldHaveCause() }81 .shouldHaveMessage("Throwable should have a cause")82 }83 "shouldNotHaveCause" {84 shouldThrow<TestException> { throw TestException() }.shouldNotHaveCause()85 shouldThrow<IOException> { throw FileNotFoundException("this_file.txt not found") }.shouldNotHaveCause()86 shouldThrow<AssertionError> { CompleteTestException().shouldNotHaveCause() }87 .shouldHaveMessage("Throwable should not have a cause")88 }89 "shouldHaveCauseInstanceOf" {90 shouldThrow<CompleteTestException> { throw CompleteTestException() }.shouldHaveCauseInstanceOf<FileNotFoundException>()91 shouldThrow<CompleteTestException> { throw CompleteTestException() }.shouldHaveCauseInstanceOf<IOException>()92 shouldThrow<AssertionError> { CompleteTestException().shouldHaveCauseInstanceOf<RuntimeException>() }93 .shouldHaveMessage("Throwable cause should be of type java.lang.RuntimeException or it's descendant, but instead got java.io.FileNotFoundException")94 }95 "shouldNotHaveCauseInstanceOf" {96 shouldThrow<CompleteTestException> { throw CompleteTestException() }.shouldNotHaveCauseInstanceOf<TestException>()97 shouldThrow<AssertionError> { CompleteTestException().shouldNotHaveCauseInstanceOf<FileNotFoundException>() }98 .shouldHaveMessage("Throwable cause should not be of type java.io.FileNotFoundException or it's descendant")99 }100 "shouldHaveCauseOfType" {101 shouldThrow<CompleteTestException> { throw CompleteTestException() }.shouldHaveCauseOfType<FileNotFoundException>()102 shouldThrow<AssertionError> { CompleteTestException().shouldHaveCauseOfType<RuntimeException>() }103 .shouldHaveMessage("Throwable cause should be of type java.lang.RuntimeException, but instead got java.io.FileNotFoundException")104 }105 "shouldNotHaveCauseOfType" {106 shouldThrow<CompleteTestException> { throw CompleteTestException() }.shouldNotHaveCauseOfType<IOException>()107 shouldThrow<AssertionError> { CompleteTestException().shouldNotHaveCauseOfType<FileNotFoundException>() }108 .shouldHaveMessage("Throwable cause should not be of type java.io.FileNotFoundException")109 }110 }111 "shouldThrowExactly" - {112 "shouldHaveMessage" {113 shouldThrowExactly<FileNotFoundException> { throw FileNotFoundException("this_file.txt not found") } shouldHaveMessage "this_file.txt not found"114 shouldThrowExactly<TestException> { throw TestException() } shouldHaveMessage "This is a test exception"115 shouldThrowExactly<CompleteTestException> { throw CompleteTestException() } shouldHaveMessage "This is a complete test exception"116 }117 "shouldNotHaveMessage" {118 shouldThrowExactly<FileNotFoundException> { throw FileNotFoundException("this_file.txt not found") } shouldNotHaveMessage "random message"119 shouldThrowExactly<TestException> { throw TestException() } shouldNotHaveMessage "This is a complete test exception"120 shouldThrowExactly<CompleteTestException> { throw CompleteTestException() } shouldNotHaveMessage "This is a test exception"121 }122 "shouldHaveCause" {123 shouldThrowExactly<CompleteTestException> { throw CompleteTestException() }.shouldHaveCause()124 shouldThrowExactly<CompleteTestException> { throw CompleteTestException() }.shouldHaveCause {125 it shouldHaveMessage "file.txt not found"126 }127 }128 "shouldNotHaveCause" {129 shouldThrowExactly<TestException> { throw TestException() }.shouldNotHaveCause()130 shouldThrowExactly<FileNotFoundException> { throw FileNotFoundException("this_file.txt not found") }.shouldNotHaveCause()131 }132 "shouldHaveCauseInstanceOf" {133 shouldThrowExactly<CompleteTestException> { throw CompleteTestException() }.shouldHaveCauseInstanceOf<FileNotFoundException>()134 shouldThrowExactly<CompleteTestException> { throw CompleteTestException() }.shouldHaveCauseInstanceOf<IOException>()135 }136 "shouldNotHaveCauseInstanceOf" {137 shouldThrowExactly<CompleteTestException> { throw CompleteTestException() }.shouldNotHaveCauseInstanceOf<TestException>()138 }139 "shouldHaveCauseOfType" {140 shouldThrowExactly<CompleteTestException> { throw CompleteTestException() }.shouldHaveCauseOfType<FileNotFoundException>()141 }142 "shouldNotHaveCauseOfType" {143 shouldThrowExactly<CompleteTestException> { throw CompleteTestException() }.shouldNotHaveCauseOfType<IOException>()144 }145 }146 "result" - {147 "shouldHaveMessage" {148 Result.failure<Any>(FileNotFoundException("this_file.txt not found"))149 .exceptionOrNull()!! shouldHaveMessage "this_file.txt not found"150 Result.failure<Any>(TestException()).exceptionOrNull()!! shouldHaveMessage "This is a test exception"151 Result.failure<Any>(CompleteTestException())152 .exceptionOrNull()!! shouldHaveMessage "This is a complete test exception"153 }154 "shouldNotHaveMessage" {155 Result.failure<Any>(FileNotFoundException("this_file.txt not found"))156 .exceptionOrNull()!! shouldNotHaveMessage "random message"157 Result.failure<Any>(TestException())158 .exceptionOrNull()!! shouldNotHaveMessage "This is a complete test exception"159 Result.failure<Any>(CompleteTestException())160 .exceptionOrNull()!! shouldNotHaveMessage "This is a test exception"161 }162 "shouldHaveCause" {163 Result.failure<Any>(CompleteTestException()).exceptionOrNull()!!.shouldHaveCause()164 Result.failure<Any>(CompleteTestException()).exceptionOrNull()!!.shouldHaveCause {165 it shouldHaveMessage "file.txt not found"166 }167 }168 "shouldNotHaveCause" {169 Result.failure<Any>(TestException()).exceptionOrNull()!!.shouldNotHaveCause()170 Result.failure<Any>(FileNotFoundException("this_file.txt not found")).exceptionOrNull()!!171 .shouldNotHaveCause()172 }173 "shouldHaveCauseInstanceOf" {174 Result.failure<Any>(CompleteTestException()).exceptionOrNull()!!175 .shouldHaveCauseInstanceOf<FileNotFoundException>()176 Result.failure<Any>(CompleteTestException()).exceptionOrNull()!!.shouldHaveCauseInstanceOf<IOException>()177 }178 "shouldNotHaveCauseInstanceOf" {179 Result.failure<Any>(CompleteTestException()).exceptionOrNull()!!180 .shouldNotHaveCauseInstanceOf<TestException>()181 }182 "shouldHaveCauseOfType" {183 Result.failure<Any>(CompleteTestException()).exceptionOrNull()!!184 .shouldHaveCauseOfType<FileNotFoundException>()185 }186 "shouldNotHaveCauseOfType" {187 Result.failure<Any>(CompleteTestException()).exceptionOrNull()!!.shouldNotHaveCauseOfType<IOException>()188 }189 }190 "shouldThrowWithMessage" {191 shouldThrowWithMessage<TestException>("This is a test exception") {192 throw TestException()193 } shouldHaveMessage "This is a test exception"194 }195 }196 class TestException : Throwable("This is a test exception")197 class CompleteTestException :198 Throwable("This is a complete test exception", FileNotFoundException("file.txt not found"))199}...

Full Screen

Full Screen

ExtendedHttpClientTest.kt

Source:ExtendedHttpClientTest.kt Github

copy

Full Screen

1/*2 * Copyright (C) 2022 Edgar Asatryan3 *4 * Licensed under the Apache License, Version 2.0 (the "License");5 * you may not use this file except in compliance with the License.6 * You may obtain a copy of the License at7 *8 * http://www.apache.org/licenses/LICENSE-2.09 *10 * Unless required by applicable law or agreed to in writing, software11 * distributed under the License is distributed on an "AS IS" BASIS,12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.13 * See the License for the specific language governing permissions and14 * limitations under the License.15 */16package io.github.nstdio.http.ext17import io.github.nstdio.http.ext.ExtendedHttpClient.Builder18import io.kotest.assertions.throwables.shouldThrowExactly19import io.kotest.matchers.throwable.shouldHaveCause20import io.kotest.matchers.types.shouldBeSameInstanceAs21import org.assertj.core.api.Assertions.assertThatExceptionOfType22import org.junit.jupiter.api.BeforeEach23import org.junit.jupiter.api.Nested24import org.junit.jupiter.api.Test25import org.junit.jupiter.params.ParameterizedTest26import org.junit.jupiter.params.provider.MethodSource27import org.junit.jupiter.params.provider.ValueSource28import org.mockito.BDDMockito.given29import org.mockito.BDDMockito.inOrder30import org.mockito.Mockito.any31import org.mockito.Mockito.mock32import java.io.IOException33import java.net.Authenticator34import java.net.CookieHandler35import java.net.ProxySelector36import java.net.SocketTimeoutException37import java.net.URI38import java.net.http.HttpClient39import java.net.http.HttpClient.Version40import java.net.http.HttpRequest41import java.net.http.HttpResponse.BodyHandler42import java.net.http.HttpResponse.BodyHandlers.ofString43import java.time.Clock44import java.time.Duration45import java.util.concurrent.CompletionException46import java.util.concurrent.Executor47import javax.net.ssl.SSLContext48import javax.net.ssl.SSLParameters49internal class ExtendedHttpClientTest {50 private lateinit var client: ExtendedHttpClient51 private lateinit var mockHttpClient: HttpClient52 @BeforeEach53 fun setUp() {54 mockHttpClient = mock(HttpClient::class.java)55 client = ExtendedHttpClient(mockHttpClient, NullCache.INSTANCE, Clock.systemUTC())56 }57 @ParameterizedTest58 @ValueSource(classes = [IOException::class, InterruptedException::class, SocketTimeoutException::class])59 fun shouldPropagateExceptions(th: Class<Throwable>) {60 //given61 val request = HttpRequest.newBuilder().uri(URI.create("https://example.com")).build()62 given(mockHttpClient.send(any(), any<BodyHandler<Any>>())).willThrow(th)63 //when + then64 assertThatExceptionOfType(th)65 .isThrownBy { client.send(request, ofString()) }66 }67 @ParameterizedTest68 @MethodSource("notUnwrappedExceptions")69 fun `Should throw CompletionException with cause`(th: Throwable) {70 //given71 val request = HttpRequest.newBuilder().uri(URI.create("https://example.com")).build()72 given(mockHttpClient.send(any(), any<BodyHandler<Any>>())).willThrow(th)73 //when + then74 shouldThrowExactly<CompletionException> { client.send(request, ofString()) }75 .shouldHaveCause { it.shouldBeSameInstanceAs(th) }76 }77 @Test78 fun `Should forward calls to delegate`() {79 //when80 client.cookieHandler()81 client.connectTimeout()82 client.followRedirects()83 client.proxy()84 client.sslContext()85 client.sslParameters()86 client.authenticator()87 client.version()88 client.executor()89 client.newWebSocketBuilder()90 //then91 val inOrder = inOrder(mockHttpClient)92 inOrder.verify(mockHttpClient).cookieHandler()93 inOrder.verify(mockHttpClient).connectTimeout()94 inOrder.verify(mockHttpClient).followRedirects()95 inOrder.verify(mockHttpClient).proxy()96 inOrder.verify(mockHttpClient).sslContext()97 inOrder.verify(mockHttpClient).sslParameters()98 inOrder.verify(mockHttpClient).authenticator()99 inOrder.verify(mockHttpClient).version()100 inOrder.verify(mockHttpClient).executor()101 inOrder.verify(mockHttpClient).newWebSocketBuilder()102 }103 @Nested104 inner class BuilderTest {105 @Test106 fun `Should forward calls to delegate`() {107 //given108 val mockDelegate = mock(HttpClient.Builder::class.java)109 val mockCookieHandler = mock(CookieHandler::class.java)110 val mockSSLContext = mock(SSLContext::class.java)111 val mockSSLParameters = mock(SSLParameters::class.java)112 val mockProxySelector = mock(ProxySelector::class.java)113 val mockAuthenticator = mock(Authenticator::class.java)114 val mockExecutor = mock(Executor::class.java)115 val builder = Builder(mockDelegate)116 //when117 builder118 .cookieHandler(mockCookieHandler)119 .connectTimeout(Duration.ofSeconds(30))120 .sslContext(mockSSLContext)121 .sslParameters(mockSSLParameters)122 .version(Version.HTTP_2)123 .priority(500)124 .followRedirects(HttpClient.Redirect.ALWAYS)125 .proxy(mockProxySelector)126 .authenticator(mockAuthenticator)127 .executor(mockExecutor)128 //then129 val inOrder = inOrder(mockDelegate)130 inOrder.verify(mockDelegate).cookieHandler(mockCookieHandler)131 inOrder.verify(mockDelegate).connectTimeout(Duration.ofSeconds(30))132 inOrder.verify(mockDelegate).sslContext(mockSSLContext)133 inOrder.verify(mockDelegate).sslParameters(mockSSLParameters)134 inOrder.verify(mockDelegate).version(Version.HTTP_2)135 inOrder.verify(mockDelegate).priority(500)136 inOrder.verify(mockDelegate).followRedirects(HttpClient.Redirect.ALWAYS)137 inOrder.verify(mockDelegate).proxy(mockProxySelector)138 inOrder.verify(mockDelegate).authenticator(mockAuthenticator)139 inOrder.verify(mockDelegate).executor(mockExecutor)140 }141 }142 companion object {143 @JvmStatic144 fun notUnwrappedExceptions(): List<Throwable> {145 return listOf(146 RuntimeException("abc"),147 IllegalStateException("abc"),148 OutOfMemoryError("abcd")149 )150 }151 }152}...

Full Screen

Full Screen

PayloadGenerationTests.kt

Source:PayloadGenerationTests.kt Github

copy

Full Screen

1package io.dwsoft.restx.core.response.payload2import io.dwsoft.restx.core.dummy3import io.dwsoft.restx.core.mock4import io.kotest.assertions.throwables.shouldThrow5import io.kotest.core.spec.style.FunSpec6import io.kotest.matchers.shouldBe7import io.kotest.matchers.throwable.shouldHaveCause8import io.mockk.every9import io.mockk.verify10private typealias SingleErrorGeneratorFactory =11 (CauseResolver<Any>, CodeResolver<Any>, MessageResolver<Any>) -> SingleErrorPayloadGenerator<Any>12abstract class SingleErrorPayloadGeneratorTestsBase<R : SingleErrorPayload>(13 createGenerator: SingleErrorGeneratorFactory,14 additionalTestsInitBlock: FunSpec.() -> Unit = {}15) : FunSpec({16 test("exception is thrown in case of cause resolver failure") {17 val exCause = CauseResolvingException("")18 val sut = createGenerator(19 mock { every { causeOf(any()) } throws exCause },20 dummy(),21 dummy()22 )23 shouldThrow<PayloadGenerationException> { sut.payloadOf(Any().causeKey("")) }24 .shouldHaveCause { it shouldBe exCause }25 }26 test("exception is thrown in case of code resolver failure") {27 val exCause = CodeResolvingException("")28 val sut = createGenerator(29 dummy(),30 mock { every { codeFor(any()) } throws exCause },31 dummy()32 )33 shouldThrow<PayloadGenerationException> { sut.payloadOf(Any().causeKey("")) }34 .shouldHaveCause { it shouldBe exCause }35 }36 test("exception is thrown in case of message resolver failure") {37 val exCause = CodeResolvingException("")38 val sut = createGenerator(39 dummy(),40 dummy(),41 mock { every { messageFor(any()) } throws exCause }42 )43 shouldThrow<PayloadGenerationException> { sut.payloadOf(Any().causeKey("")) }44 .shouldHaveCause { it shouldBe exCause }45 }46 this.apply(additionalTestsInitBlock)47})48class OperationErrorPayloadGeneratorTests : SingleErrorPayloadGeneratorTestsBase<OperationError>(49 { causeResolver, codeResolver, messageResolver ->50 OperationErrorPayloadGenerator(causeResolver, codeResolver, messageResolver)51 },52 {53 test("payload with defined data is returned") {54 val cause = Any().causeKey("")55 val code = "code"56 val message = "message".asMessage()57 val generator = OperationErrorPayloadGenerator<Any>({ cause }, { code }, { message })58 val payload = generator.payloadOf(Any())59 payload shouldBe OperationError(code, message)60 }61 }62)63class RequestDataErrorPayloadGeneratorTests : SingleErrorPayloadGeneratorTestsBase<RequestDataError>(64 { causeResolver, codeResolver, messageResolver ->65 RequestDataErrorPayloadGenerator(causeResolver, codeResolver, messageResolver, dummy())66 },67 {68 test("payload with defined data is returned") {69 val cause = Any().causeKey("")70 val code = "code"71 val message = "message".asMessage()72 val source = RequestDataError.Source.query("query")73 val generator = RequestDataErrorPayloadGenerator<Any>({ cause }, { code }, { message }, { source })74 val payload = generator.payloadOf(Any())75 payload shouldBe RequestDataError(code, message, source)76 }77 test("exception is thrown in case data error source cannot be resolved") {78 val exCause = DataErrorSourceResolvingException()79 val generator = RequestDataErrorPayloadGenerator<Any>(80 dummy(),81 dummy(),82 dummy(),83 mock { every { sourceOf(any()) } throws exCause }84 )85 shouldThrow<PayloadGenerationException> { generator.payloadOf(Any()) }86 .shouldHaveCause { it shouldBe exCause }87 }88 }89)90class MultiErrorPayloadGeneratorTests : FunSpec({91 test("sub-errors extractor function is called") {92 val extractor = mock<SubErrorExtractor<Any, Any>>()93 val generator = MultiErrorPayloadGenerator(extractor, dummy())94 val fault = Any()95 runCatching { generator.payloadOf(fault) }96 verify { extractor(fault) }97 }98 test("sub-error payload generator is called for each sub-error extracted") {99 val subError1 = Any()100 val subError2 = Any()101 val subErrorPayloadGenerator = mock<SingleErrorPayloadGenerator<Any>> {102 every { this@mock.payloadOf(any()) } returns dummy()103 }104 val generator = MultiErrorPayloadGenerator(105 SubErrorExtractor { listOf(subError1, subError2) },106 subErrorPayloadGenerator107 )108 val fault = Any()109 generator.payloadOf(fault)110 verify { subErrorPayloadGenerator.payloadOf(subError1) }111 verify { subErrorPayloadGenerator.payloadOf(subError2) }112 }113 test("exception is thrown when no sub-errors are extracted") {114 val generator = MultiErrorPayloadGenerator<Any, Any>({ emptyList() }, dummy())115 shouldThrow<PayloadGenerationException> { generator.payloadOf(Any()) }116 }117 test("multi error payload containing errors generated for sub-errors is returned") {118 val expectedPayloadContent = listOf<SingleErrorPayload>(dummy(), dummy())119 val subErrorPayloadGenerator = mock<SingleErrorPayloadGenerator<Any>> {120 every { this@mock.payloadOf(any()) } returnsMany expectedPayloadContent121 }122 val generator = MultiErrorPayloadGenerator(123 SubErrorExtractor { listOf(dummy(), dummy()) },124 subErrorPayloadGenerator125 )126 val result = generator.payloadOf(Any())127 result shouldBe MultiErrorPayload(expectedPayloadContent)128 }129})...

Full Screen

Full Screen

BodyHandlersTest.kt

Source:BodyHandlersTest.kt Github

copy

Full Screen

1/*2 * Copyright (C) 2022 Edgar Asatryan3 *4 * Licensed under the Apache License, Version 2.0 (the "License");5 * you may not use this file except in compliance with the License.6 * You may obtain a copy of the License at7 *8 * http://www.apache.org/licenses/LICENSE-2.09 *10 * Unless required by applicable law or agreed to in writing, software11 * distributed under the License is distributed on an "AS IS" BASIS,12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.13 * See the License for the specific language governing permissions and14 * limitations under the License.15 */16package io.github.nstdio.http.ext17import io.github.nstdio.http.ext.spi.Classpath18import io.kotest.assertions.throwables.shouldThrowExactly19import io.kotest.matchers.nulls.shouldNotBeNull20import io.kotest.matchers.throwable.shouldHaveCause21import mockwebserver3.MockResponse22import mockwebserver3.MockWebServer23import mockwebserver3.junit5.internal.MockWebServerExtension24import org.junit.jupiter.api.Assumptions.assumeTrue25import org.junit.jupiter.api.BeforeEach26import org.junit.jupiter.api.Nested27import org.junit.jupiter.api.Test28import org.junit.jupiter.api.extension.ExtendWith29import java.io.UncheckedIOException30import java.net.http.HttpClient31import java.net.http.HttpRequest32@ExtendWith(MockWebServerExtension::class)33internal class BodyHandlersTest(private val mockWebServer: MockWebServer) {34 @Nested35 internal inner class OfJsonTest {36 private val client = HttpClient.newHttpClient()37 @BeforeEach38 fun setUp() {39 assumeTrue { ALL_JSON.any { Classpath.isPresent(it) } }40 }41 @Test42 fun shouldProperlyReadJson() {43 //given44 val request = HttpRequest.newBuilder(mockWebServer.url("/get").toUri()).build()45 mockWebServer.enqueue(46 MockResponse().setResponseCode(200).setBody(47 """48 {49 "args": {},50 "headers": {51 "Accept": "application/json",52 "Accept-Encoding": "gzip, deflate, br",53 "Accept-Language": "en-US,en;q=0.5",54 "Host": "httpbin.org",55 "Referer": "https://httpbin.org/",56 "Sec-Fetch-Dest": "empty",57 "Sec-Fetch-Mode": "cors",58 "Sec-Fetch-Site": "same-origin",59 "User-Agent": "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:99.0) Gecko/20100101 Firefox/99.0",60 "X-Amzn-Trace-Id": "Root=1-6259c64f-002692993e9394f43151cfd7"61 },62 "origin": "37.252.83.253",63 "url": "https://httpbin.org/get"64 }65 """.trimIndent()66 )67 )68 //when69 val body1 = client.sendAsync(request, BodyHandlers.ofJson(Any::class.java)).thenApply { it.body().get() }.join()70 //then71 body1.shouldNotBeNull()72 }73 @Test74 fun shouldThrowUncheckedExceptionIfCannotRead() {75 //given76 val request = HttpRequest.newBuilder(mockWebServer.url("/get").toUri()).build()77 mockWebServer.enqueue(78 MockResponse().setResponseCode(200).setBody("<html></html>")79 )80 //when81 shouldThrowExactly<UncheckedIOException> {82 client.send(request, BodyHandlers.ofJson(Any::class.java)).body().get()83 }.shouldHaveCause()84 }85 }86}...

Full Screen

Full Screen

Throwable.shouldHaveCause

Using AI Code Generation

copy

Full Screen

1throwable.shouldHaveCause<IllegalArgumentException>()2throwable.shouldHaveMessage("Some message")3throwable.shouldHaveMessageContaining("Some message")4throwable.shouldHaveNoCause()5throwable.shouldHaveNoSuppressedExceptions()6throwable.shouldHaveSuppressedException<IllegalArgumentException>()7throwable.shouldHaveSuppressedException<IllegalArgumentException>("Some message")8throwable.shouldHaveSuppressedException<IllegalArgumentException>("Some message") { }9throwable.shouldHaveSuppressedException<IllegalArgumentException> { }10throwable.shouldHaveSuppressedException<IllegalArgumentException> { it shouldHaveMessage "Some message" }11throwable.shouldHaveSuppressedException<IllegalArgumentException> { it shouldHaveMessageContaining "Some message" }12throwable.shouldHaveSuppressedException<IllegalArgumentException> { it shouldHaveNoCause() }13throwable.shouldHaveSuppressedException<IllegalArgumentException> { it shouldHaveSuppressedException<IllegalArgumentException>() }14throwable.shouldHaveSuppressedException<IllegalArgumentException> { it shouldHaveSuppressed

Full Screen

Full Screen

Throwable.shouldHaveCause

Using AI Code Generation

copy

Full Screen

1shouldThrow<IllegalArgumentException> {2throw IllegalArgumentException("message")3}.shouldHaveCause(IllegalStateException())4shouldThrow<IllegalArgumentException> {5throw IllegalArgumentException("message")6}.shouldHaveCause(IllegalStateException::class)7shouldThrow<IllegalArgumentException> {8throw IllegalArgumentException("message")9}.shouldHaveCause<IllegalStateException>()10shouldThrow<IllegalArgumentException> {11throw IllegalArgumentException("message")12}.shouldHaveCause<IllegalStateException> { it.message shouldBe "some message" }13shouldThrow<IllegalArgumentException> {14throw IllegalArgumentException("message")15}.shouldHaveCause<IllegalStateException> { it.message shouldBe "some message" }16shouldThrow<IllegalArgumentException> {17throw IllegalArgumentException("message")18}.shouldHaveCause<IllegalStateException> { it.message shouldBe "some message" }19shouldThrow<IllegalArgumentException> {20throw IllegalArgumentException("message")21}.shouldHaveCause<IllegalStateException> { it.message shouldBe "some message" }22shouldThrow<IllegalArgumentException> {23throw IllegalArgumentException("message")24}.shouldHaveCause<IllegalStateException> { it.message shouldBe "some message" }25shouldThrow<IllegalArgumentException> {26throw IllegalArgumentException("message")27}.shouldHaveCause<IllegalStateException> { it.message shouldBe "some message" }28shouldThrow<IllegalArgumentException> {29throw IllegalArgumentException("message")30}.shouldHaveCause<IllegalStateException> { it.message shouldBe "some message" }31shouldThrow<IllegalArgumentException> {32throw IllegalArgumentException("message")33}.shouldHaveCause<IllegalStateException> { it.message shouldBe

Full Screen

Full Screen

Throwable.shouldHaveCause

Using AI Code Generation

copy

Full Screen

1class ThrowableMatchersTest : FunSpec({2test("should have cause") {3val cause = IllegalArgumentException("cause")4val exception = RuntimeException("exception", cause)5exception.shouldHaveCause<IllegalArgumentException>()6exception.shouldHaveCause<IllegalArgumentException>("exception")7exception.shouldHaveCause<IllegalArgumentException>("exception", cause)8}9})10class ThrowableMatchersTest : FunSpec({11test("should have cause") {12val cause = IllegalArgumentException("cause")13val exception = RuntimeException("exception", cause)14exception.shouldHaveCauseInstanceOf<IllegalArgumentException>()15exception.shouldHaveCauseInstanceOf<IllegalArgumentException>("exception")16}17})18class ThrowableMatchersTest : FunSpec({19test("should have message") {20val exception = RuntimeException("exception")21exception.shouldHaveMessage("exception")22}23})24class ThrowableMatchersTest : FunSpec({25test("should have message containing") {26val exception = RuntimeException("exception")27exception.shouldHaveMessageContaining("excep")28}29})30class ThrowableMatchersTest : FunSpec({31test("should have message matching") {32val exception = RuntimeException("exception")33exception.shouldHaveMessageMatching("excep.*")34}35})36class ThrowableMatchersTest : FunSpec({37test("should have no cause") {38val exception = RuntimeException("exception")39exception.shouldHaveNoCause()40}41})42class ThrowableMatchersTest : FunSpec({43test("should have no suppressed") {44val exception = RuntimeException("exception")45exception.shouldHaveNoSuppressed()46}47})48class ThrowableMatchersTest : FunSpec({49test("should have suppressed") {

Full Screen

Full Screen

Throwable.shouldHaveCause

Using AI Code Generation

copy

Full Screen

1@DisplayName ( "should have cause" ) @Test fun `should have cause` ( ) { val exception = Exception ( "test" , Exception ( "cause" ) ) exception shouldHaveCause Exception :: class exception shouldHaveCause Exception :: class . withMessage ( "cause" ) }2@DisplayName ( "should have cause instance of" ) @Test fun `should have cause instance of` ( ) { val exception = Exception ( "test" , Exception ( "cause" ) ) exception shouldHaveCauseInstanceOf Exception :: class }3@DisplayName ( "should have no cause" ) @Test fun `should have no cause` ( ) { val exception = Exception ( "test" ) exception shouldHaveNoCause }4@DisplayName ( "should have cause" ) @Test fun `should have cause` ( ) { val exception = Exception ( "test" , Exception ( "cause" ) ) exception shouldHaveCause Exception :: class exception shouldHaveCause Exception :: class . withMessage ( "cause" ) }5@DisplayName ( "should have cause instance of" ) @Test fun `should have cause instance of` ( ) { val exception = Exception ( "test" , Exception ( "cause" ) ) exception shouldHaveCauseInstanceOf Exception :: class }6@DisplayName ( "should have no cause" ) @Test fun `should have no cause` ( ) { val exception = Exception ( "test" ) exception shouldHaveNoCause }7@DisplayName ( "should have cause" ) @Test fun `should have cause` ( ) { val exception = Exception ( "test" , Exception ( "cause" ) ) exception shouldHaveCause Exception :: class exception shouldHaveCause Exception :: class . withMessage ( "cause" ) }

Full Screen

Full Screen

Throwable.shouldHaveCause

Using AI Code Generation

copy

Full Screen

1class MyTest : StringSpec({2 "should throw exception" {3 val exception = assertThrows<ArithmeticException> {4 throw ArithmeticException("Test")5 }6 exception.shouldHaveCause<ArithmeticException>()7 }8})9 at io.kotest.core.spec.style.StringSpec.<init>(StringSpec.kt:23)10 at com.example.MyTest.<init>(MyTest.kt:7)11 at com.example.MyTestKt.main(MyTest.kt:11)12 at com.example.MyTestKt.main(MyTest.kt)13 at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:583)14 at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178)15 at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:521)

Full Screen

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful