Open philipa opened 10 years ago
The first thing I did was create my own matcher like this.
I've found this Hamcrest matcher useful (kotlin):
import org.hamcrest.Description
import org.hamcrest.Matcher
import org.hamcrest.TypeSafeMatcher
import org.slf4j.Marker
import uk.org.lidalia.slf4jext.Level
import uk.org.lidalia.slf4jtest.LoggingEvent
data class LoggingEventMatcher(
private val level: Matcher<Level>? = null,
private val mdc: Matcher<Map<String, String>>? = null,
private val marker: Matcher<Marker>? = null,
private val throwable: Matcher<Throwable>? = null,
private val message: Matcher<String>? = null,
private val arguments: Matcher<List<Any>>? = null
) : TypeSafeMatcher<LoggingEvent>() {
override fun describeTo(description: Description?) {
description?.appendText("a LoggingEvent")
description?.appendText("[")
appendDescriptionForMatchers(description, linkedMapOf(
"level" to level,
"mdc" to mdc,
"marker" to marker,
"throwable" to throwable,
"message" to message,
"arguments" to arguments
))
description?.appendText("]")
}
private fun appendDescriptionForMatchers(description: Description?, matchers: Map<String, Matcher<*>?>) {
var addSeparator = false
for ((name, matcher) in matchers) {
if (matcher != null) {
if (addSeparator) {
description?.appendText(",")
}
description?.appendText(name)!!.appendText("=").appendDescriptionOf(matcher)
addSeparator = true
}
}
}
override fun matchesSafely(item: LoggingEvent): Boolean {
return (level == null || level.matches(item.level))
&& (mdc == null || mdc.matches(item.mdc))
&& (marker == null || marker.matches(item.marker.orNull()))
&& (throwable == null || throwable.matches(item.throwable.orNull()))
&& (message == null || message.matches(item.message))
&& (arguments == null || arguments.matches(item.arguments))
}
}
then I can assert any part of the logging event like below (kotlin again)
assertThat(logger.loggingEvents, hasItem(LoggingEventMatcher(level = equalTo(Level.ERROR), throwable = instanceOf(RuntimeException::class.java))))
I'm finding the following useful:
So I can say
Perhaps there should be a LoggingEventMatchers?