我有一个像这样简单的类:
package com.example.howtomocktest
import groovy.util.logging.Slf4j
import java.nio.channels.NotYetBoundException
@Slf4j
class ErrorLogger {
static void handleExceptions(Closure closure) {
try {
closure()
}catch (UnsupportedOperationException|NotYetBoundException ex) {
log.error ex.message
} catch (Exception ex) {
log.error 'Processing exception {}', ex
}
}
}
我想为此编写一个测试,以下是一个框架:
package com.example.howtomocktest
import org.slf4j.Logger
import spock.lang.Specification
import java.nio.channels.NotYetBoundException
import static com.example.howtomocktest.ErrorLogger.handleExceptions
class ErrorLoggerSpec extends Specification {
private static final UNSUPPORTED_EXCEPTION = { throw UnsupportedOperationException }
private static final NOT_YET_BOUND = { throw NotYetBoundException }
private static final STANDARD_EXCEPTION = { throw Exception }
private Logger logger = Mock(Logger.class)
def setup() {
}
def "Message logged when UnsupportedOperationException is thrown"() {
when:
handleExceptions {UNSUPPORTED_EXCEPTION}
then:
notThrown(UnsupportedOperationException)
1 * logger.error(_ as String) // doesn't work
}
def "Message logged when NotYetBoundException is thrown"() {
when:
handleExceptions {NOT_YET_BOUND}
then:
notThrown(NotYetBoundException)
1 * logger.error(_ as String) // doesn't work
}
def "Message about processing exception is logged when standard Exception is thrown"() {
when:
handleExceptions {STANDARD_EXCEPTION}
then:
notThrown(STANDARD_EXCEPTION)
1 * logger.error(_ as String) // doesn't work
}
}
ErrorLogger类中的记录器是通过StaticLoggerBinder提供的,所以我的问题是 - 如何使其工作,以便这些检查"1 * logger.error(_ as String)"能够工作?我找不到在ErrorLogger类内部模拟该记录器的正确方法。我考虑过反射和某种方式访问它,此外还有一个使用mockito注入的想法(但由于Slf4j注释而在该类中甚至没有对象的引用,如何做到呢!)感谢您提前给出所有反馈和建议。
编辑:这是测试的输出,即使1*logger.error(_)也不起作用。
Too few invocations for:
1*logger.error() (0 invocations)
Unmatched invocations (ordered by similarity):