Skip to content

Instantly share code, notes, and snippets.

@Manjago
Created July 9, 2021 11:59
Show Gist options
  • Save Manjago/98ff0aad5c57e363973e1a4cbadb569f to your computer and use it in GitHub Desktop.
Save Manjago/98ff0aad5c57e363973e1a4cbadb569f to your computer and use it in GitHub Desktop.
Kotlin Asserting Log Messages With JUnit
package ru.mts.ftb.ftbotpservice.utils
import ch.qos.logback.classic.Level
import ch.qos.logback.classic.spi.ILoggingEvent
import ch.qos.logback.core.read.ListAppender
//inspired by https://www.baeldung.com/junit-asserting-logs
class MemoryAppender : ListAppender<ILoggingEvent?>() {
fun reset() = list.clear()
fun contains(level: Level, string: String): Boolean = list.any {
it?.message.toString().contains(string) && it?.level == level
}
fun countEventsForLogger(loggerName: String): Int = list.count {
it?.loggerName?.contains(loggerName) == true
}
fun search(string: String): List<ILoggingEvent> = list.asSequence().filter {
it?.message.toString().contains(string)
}.filterNotNull().toList()
fun search(level: Level, string: String): List<ILoggingEvent> = list.asSequence().filter {
it?.message.toString().contains(string) && it?.level == level
}.filterNotNull().toList()
fun getSize(): Int = list.size
fun getLoggedEvents(): List<ILoggingEvent?> = list.toList()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment