Home > database >  How to write a MockK unit test for the following code involving exceptions
How to write a MockK unit test for the following code involving exceptions

Time:04-09

I just started coding in Kotlin and I've never used MockK before. I want to know how to write a mockk test for the schedule() function and to test the RejectedExecutionException.

  fun schedule() {
            try {
                executor.scheduleAtFixedRate(this, 0, 1, TimeUnit.HOURS)
            } catch (e: RejectedExecutionException) {
                logger.warn("Encountered an exception: $e")
            }
        }

CodePudding user response:

You can test exceptions using assertThrows:

// executor must be defined as mockk 
every { executor.scheduleAtFixedRate(any(), any(), any(), any()) } throws RejectedExecutionException("Exception Message")
val ex = assertThrows<RejectedExecutionException> {
            obj.schedule()
        }
ex.message shouldContainIgnoringCase "message"
  • Related