How to use KFunction.getExpectedException method of io.kotest.core.spec.style.AnnotationSpec class

Best Kotest code snippet using io.kotest.core.spec.style.AnnotationSpec.KFunction.getExpectedException

AnnotationSpec.kt

Source:AnnotationSpec.kt Github

copy

Full Screen

1package io.kotest.core.spec.style2import io.kotest.core.extensions.Extension3import io.kotest.core.names.TestName4import io.kotest.core.source.sourceRef5import io.kotest.core.spec.RootTest6import io.kotest.core.spec.Spec7import io.kotest.core.test.TestCase8import io.kotest.core.test.TestResult9import io.kotest.core.test.TestScope10import io.kotest.core.test.TestType11import io.kotest.mpp.unwrapIfReflectionCall12import kotlin.reflect.KClass13import kotlin.reflect.KFunction14import kotlin.reflect.full.callSuspend15import kotlin.reflect.full.memberFunctions16import kotlin.reflect.jvm.isAccessible17typealias Test = AnnotationSpec.Test18abstract class AnnotationSpec : Spec() {19 override suspend fun beforeSpec(spec: Spec) {20 executeBeforeSpecFunctions()21 }22 private suspend fun executeBeforeSpecFunctions() = this::class.findBeforeSpecFunctions().forEach {23 if (it.isSuspend) it.callSuspend(this) else it.call(this)24 }25 override suspend fun beforeTest(testCase: TestCase) {26 executeBeforeTestFunctions()27 }28 private suspend fun executeBeforeTestFunctions() = this::class.findBeforeTestFunctions().forEach {29 if (it.isSuspend) it.callSuspend(this) else it.call(this)30 }31 override suspend fun afterTest(testCase: TestCase, result: TestResult) {32 executeAfterTestFunctions()33 }34 private suspend fun executeAfterTestFunctions() = this::class.findAfterTestFunctions().forEach {35 if (it.isSuspend) it.callSuspend(this) else it.call(this)36 }37 override suspend fun afterSpec(spec: Spec) {38 executeAfterSpecFunctions()39 }40 private suspend fun executeAfterSpecFunctions() = this::class.findAfterSpecFunctions().forEach {41 if (it.isSuspend) it.callSuspend(this) else it.call(this)42 }43 private fun KFunction<*>.toIgnoredRootTest(): RootTest {44 return deriveRootTest(true)45 }46 private fun KFunction<*>.toEnabledRootTest(): RootTest {47 return deriveRootTest(false)48 }49 private fun KFunction<*>.deriveRootTest(disabled: Boolean): RootTest {50 return if (this.isExpectingException()) {51 val expected = this.getExpectedException()52 RootTest(53 name = TestName(name),54 test = callExpectingException(expected),55 source = sourceRef(),56 type = TestType.Test,57 config = null,58 disabled = disabled,59 factoryId = null,60 )61 } else {62 RootTest(63 name = TestName(name),64 test = callNotExpectingException(),65 source = sourceRef(),66 type = TestType.Test,67 config = null,68 disabled = disabled,69 factoryId = null,70 )71 }72 }73 override fun rootTests(): List<RootTest> {74 val tests = this::class.findRootTests()75 val nested = this::class.findNestedTests()76 return tests + nested77 }78 override fun globalExtensions(): List<Extension> {79 return emptyList()80 }81 private fun KFunction<*>.isExpectingException(): Boolean {82 return annotations.filterIsInstance<Test>().first().expected != Test.None::class83 }84 private fun KFunction<*>.getExpectedException(): KClass<out Throwable> {85 return annotations.filterIsInstance<Test>().first().expected86 }87 private fun KClass<*>.findRootTests(): List<RootTest> {88 return findTestFunctions().map { f ->89 f.isAccessible = true90 if (f.isIgnoredTest()) {91 f.toIgnoredRootTest()92 } else {93 f.toEnabledRootTest()94 }95 }96 }97 private fun KClass<out AnnotationSpec>.findNestedTests(): List<RootTest> {98 return nestedClasses99 .filter { kclass -> kclass.annotations.map { it.annotationClass }.contains(Nested::class) }100 .flatMap { it.findRootTests() }101 }102 private fun KFunction<*>.callExpectingException(expected: KClass<out Throwable>): suspend TestScope.() -> Unit {103 return {104 val thrown = try {105 callSuspend(this@AnnotationSpec)106 null107 } catch (t: Throwable) {108 t.unwrapIfReflectionCall()109 } ?: failNoExceptionThrown(expected)110 if (thrown::class != expected) failWrongExceptionThrown(expected, thrown)111 }112 }113 private fun KFunction<*>.callNotExpectingException(): suspend TestScope.() -> Unit {114 return {115 try {116 callSuspend(this@AnnotationSpec)117 } catch (t: Throwable) {118 throw t.unwrapIfReflectionCall()119 }120 }121 }122 private fun failNoExceptionThrown(expected: KClass<out Throwable>): Nothing {123 throw AssertionError("Expected exception of class ${expected.simpleName}, but no exception was thrown.")124 }125 private fun failWrongExceptionThrown(expected: KClass<out Throwable>, thrown: Throwable): Nothing {126 throw AssertionError("Expected exception of class ${expected.simpleName}, but ${thrown::class.simpleName} was thrown instead.")127 }128 // All annotations should be kept inside this class, to avoid any usage outside of AnnotationSpec.129 // One can only use annotations to execute code inside AnnotationSpec.130 /**131 * Marks a function to be executed before each test132 *133 * This can be used in AnnotationSpec to mark a function to be executed before every test by Kotest Engine134 * @see BeforeAll135 * @see AfterEach136 */137 annotation class BeforeEach138 /**139 * Marks a function to be executed before each test140 *141 * This can be used in AnnotationSpec to mark a function to be executed before every test by Kotest Engine142 * @see BeforeClass143 * @see After144 */145 annotation class Before146 /**147 * Marks a function to be executed before each spec148 *149 * This can be used in AnnotationSpec to mark a function to be executed before a spec by Kotest Engine.150 * @see BeforeEach151 * @see AfterAll152 */153 annotation class BeforeAll154 /**155 * Marks a function to be executed before each spec156 *157 * This can be used in AnnotationSpec to mark a function to be executed before a spec by Kotest Engine.158 * @see Before159 * @see AfterClass160 */161 annotation class BeforeClass162 /**163 * Marks a function to be executed after each test164 *165 * This can be used in AnnotationSpec to mark a function to be executed before a test by Kotest Engine.166 * @see AfterAll167 * @see BeforeEach168 */169 annotation class AfterEach170 /**171 * Marks a function to be executed after each test172 *173 * This can be used in AnnotationSpec to mark a function to be executed before a test by Kotest Engine.174 * @see AfterClass175 * @see Before176 */177 annotation class After178 /**179 * Marks a function to be executed after each spec180 *181 * This can be used in AnnotationSpec to mark a function to be executed before a spec by Kotest Engine.182 * @see AfterEach183 * @see BeforeAll184 */185 annotation class AfterAll186 /**187 * Marks a function to be executed after each spec188 *189 * This can be used in AnnotationSpec to mark a function to be executed before a spec by Kotest Engine.190 * @see After191 * @see BeforeClass192 */193 annotation class AfterClass194 /**195 * Marks a function to be executed as a Test196 *197 * This can be used in AnnotationSpec to mark a function to be executed as a test by Kotest Engine.198 *199 *200 * [expected] can be used to mark a test to expect a specific exception.201 *202 * This is useful when moving from JUnit, in which you use expected to verify for an exception.203 *204 * ```205 * @Test(expected = FooException::class)206 * fun foo() {207 * throw FooException() // Pass208 * }209 *210 * @Test(expected = FooException::class211 * fun bar() {212 * throw BarException() // Fails, FooException was expected213 * }214 * ```215 */216 annotation class Test(val expected: KClass<out Throwable> = None::class) {217 object None : Throwable()218 }219 /**220 * Marks a Test to be ignored221 *222 * This can be used in AnnotationSpec to mark a Test as Ignored.223 */224 annotation class Ignore225 annotation class Nested226}227internal fun KClass<out AnnotationSpec>.findBeforeTestFunctions() =228 findFunctionAnnotatedWithAnyOf(AnnotationSpec.BeforeEach::class, AnnotationSpec.Before::class)229internal fun KClass<out AnnotationSpec>.findBeforeSpecFunctions() =230 findFunctionAnnotatedWithAnyOf(AnnotationSpec.BeforeAll::class, AnnotationSpec.BeforeClass::class)231internal fun KClass<out AnnotationSpec>.findAfterSpecFunctions() =232 findFunctionAnnotatedWithAnyOf(AnnotationSpec.AfterAll::class, AnnotationSpec.AfterClass::class)233internal fun KClass<out AnnotationSpec>.findAfterTestFunctions() =234 findFunctionAnnotatedWithAnyOf(AnnotationSpec.AfterEach::class, AnnotationSpec.After::class)235internal fun KClass<*>.findTestFunctions(): List<KFunction<*>> =236 findFunctionAnnotatedWithAnyOf(AnnotationSpec.Test::class)237internal fun KFunction<*>.isIgnoredTest() = isFunctionAnnotatedWithAnyOf(AnnotationSpec.Ignore::class)238internal fun KClass<*>.findFunctionAnnotatedWithAnyOf(vararg annotation: KClass<*>): List<KFunction<*>> =239 memberFunctions.filter { it.isFunctionAnnotatedWithAnyOf(*annotation) }240internal fun KFunction<*>.isFunctionAnnotatedWithAnyOf(vararg annotation: KClass<*>) =241 annotations.any { it.annotationClass in annotation }...

Full Screen

Full Screen

KFunction.getExpectedException

Using AI Code Generation

copy

Full Screen

1fun testGetExpectedException() {2 val method = AnnotationSpec::class.java.getDeclaredMethod("testGetExpectedException")3 val expectedException = method.getExpectedException()4 assertEquals(NullPointerException::class.java, expectedException)5}6fun testGetExpectedException() {7 val method = StringSpec::class.java.getDeclaredMethod("testGetExpectedException")8 val expectedException = method.getExpectedException()9 assertEquals(NullPointerException::class.java, expectedException)10}11fun testGetExpectedException() {12 val method = WordSpec::class.java.getDeclaredMethod("testGetExpectedException")13 val expectedException = method.getExpectedException()14 assertEquals(NullPointerException::class.java, expectedException)15}16fun testGetExpectedException() {17 val method = BehaviorSpec::class.java.getDeclaredMethod("testGetExpectedException")18 val expectedException = method.getExpectedException()19 assertEquals(NullPointerException::class.java, expectedException)20}21fun testGetExpectedException() {22 val method = ExpectSpec::class.java.getDeclaredMethod("testGetExpectedException")23 val expectedException = method.getExpectedException()24 assertEquals(NullPointerException::class.java, expectedException)25}26fun testGetExpectedException() {27 val method = FreeSpec::class.java.getDeclaredMethod("testGetExpectedException")28 val expectedException = method.getExpectedException()29 assertEquals(NullPointerException::class.java, expectedException)30}31fun testGetExpectedException() {32 val method = FeatureSpec::class.java.getDeclaredMethod("testGetExpectedException")33 val expectedException = method.getExpectedException()34 assertEquals(NullPointerException::class.java, expectedException)35}

Full Screen

Full Screen

KFunction.getExpectedException

Using AI Code Generation

copy

Full Screen

1annotation class TestAnnotationWithException(val expectedException: KClass<out Throwable>)2@TestAnnotationWithException(AssertionError::class)3class AnnotationSpecExample : AnnotationSpec() {4 fun test1() {5 assertEquals(1, 2)6 }

Full Screen

Full Screen

KFunction.getExpectedException

Using AI Code Generation

copy

Full Screen

1class AnnotationSpecExample : AnnotationSpec() {2 fun test() {3 throw RuntimeException("This is a RuntimeException")4 }5 @Test(expectedExceptions = [RuntimeException::class])6 fun testWithExpectedException() {7 throw RuntimeException("This is a RuntimeException")8 }9 @Test(expectedExceptions = [RuntimeException::class, IOException::class])10 fun testWithMultipleExpectedExceptions() {11 throw IOException("This is an IOException")12 }13 @Test(expectedExceptions = [RuntimeException::class])14 fun testWithNoException() {15 println("This method should fail because no exception was thrown")16 }17 @Test(expectedExceptions = [RuntimeException::class])18 fun testWithDifferentException() {19 throw IOException("This is an IOException")20 }21}22class FunSpecExample : FunSpec({23 test("test") {24 throw RuntimeException("This is a RuntimeException")25 }26 test("test with expected exception") {27 throw RuntimeException("This is a RuntimeException")28 }.config(expectedExceptions = [RuntimeException::class])29 test("test with multiple expected exceptions") {30 throw IOException("This is an IOException")31 }.config(expectedExceptions = [RuntimeException::class, IOException::class])32 test("test with no exception") {33 println("This method should fail because no exception was thrown")34 }.config(expectedExceptions = [RuntimeException::class])35 test("test with different exception") {36 throw IOException("This is an IOException")37 }.config(expectedExceptions = [RuntimeException::class])38})39class FreeSpecExample : FreeSpec({40 "test" - {41 throw RuntimeException("This is a RuntimeException")42 }43 "test with expected exception" - {44 throw RuntimeException("This is a RuntimeException")45 }.config(expectedExceptions = [RuntimeException::class])46 "test with multiple expected exceptions" - {47 throw IOException("This is an IOException")48 }.config(expectedExceptions = [RuntimeException::class, IOException::class])49 "test with no exception" - {50 println("This method should fail because no exception was thrown")51 }.config(expectedExceptions = [RuntimeException::class])52 "test with different exception" - {53 throw IOException("This is an IOException")54 }.config(expected

Full Screen

Full Screen

KFunction.getExpectedException

Using AI Code Generation

copy

Full Screen

1class MyTest : AnnotationSpec () { 2 fun `test with expected exception`() { 3 assertThrows < IllegalArgumentException > { 4 throw IllegalArgumentException () 5 } 6 } 7 }8class MyTest : AnnotationSpec () { 9 fun `test with expected exception`() { 10 assertThrows < IllegalArgumentException > { 11 throw IllegalArgumentException () 12 } 13 } 14 }

Full Screen

Full Screen

KFunction.getExpectedException

Using AI Code Generation

copy

Full Screen

1@DisplayName( "MyAnnotationSpec" )2class MyAnnotationSpec : AnnotationSpec() {3@Tag( "tag1" )4fun test1() {5}6@Tag( "tag2" )7@DisplayName( "My Test" )8fun test2() {9}10@Tag( "tag3" )11@DisplayName( "My Test" )12fun test3() {13}14@Tag( "tag4" )15fun test4() {16}17@Tag( "tag5" )18fun test5() {19}20@Tag( "tag6" )21fun test6() {22}23@Tag( "tag7" )24fun test7() {25}26@Tag( "tag8" )27fun test8() {28}29@Tag( "tag9" )30fun test9() {31}32@Tag( "tag10" )33fun test10() {34}35@Tag( "tag11" )36fun test11() {37}38@Tag( "tag12" )39fun test12() {40}41@Tag( "tag13" )42fun test13() {43}44@Tag( "tag14" )45fun test14() {46}47@Tag( "tag15" )48fun test15() {49}50@Tag( "tag16" )51fun test16() {52}53@Tag( "tag17" )54fun test17() {55}56@Tag( "tag18" )57fun test18() {58}59@Tag( "tag19" )60fun test19() {61}62@Tag( "tag20" )63fun test20() {64}65@Tag( "tag21" )66fun test21() {67}68@Tag( "tag22" )69fun test22() {70}71@Tag( "tag23" )72fun test23() {73}74@Tag( "tag24" )75fun test24() {76}77@Tag( "tag25" )78fun test25() {79}80@Tag( "tag26" )81fun test26() {82}83@Tag( "tag27" )84fun test27() {85}86@Tag( "tag28" )87fun test28() {88}89@Tag( "tag29" )90fun test29() {91}

Full Screen

Full Screen

KFunction.getExpectedException

Using AI Code Generation

copy

Full Screen

1fun `test expected exception`() {2 val expectedException = func.getExpectedException()3 assertEquals(expectedException, null)4}5fun `test expected exception`() {6 val expectedException = func.getExpectedException()7 assertEquals(expectedException, null)8}9fun `test expected exception`() {10 val expectedException = func.getExpectedException()11 assertEquals(expectedException, null)12}13fun `test expected exception`() {14 val expectedException = func.getExpectedException()15 assertEquals(expectedException, null)16}17fun `test expected exception`() {18 val expectedException = func.getExpectedException()19 assertEquals(expectedException, null)20}21fun `test expected exception`() {22 val expectedException = func.getExpectedException()23 assertEquals(expectedException, null)24}25fun `test expected exception`() {26 val expectedException = func.getExpectedException()27 assertEquals(expectedException, null)28}29fun `test expected exception`() {

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