這是一個想法,你沒有問完全這個問題,但在grails用戶組中提出了同樣的問題。我也在這裏發佈我的答案,以傳播知識。
如果您在類中明確指出def log = org.apache.commons.logging.LogFactory.getLog(this),而不是依賴於依賴注入,就像在grails用戶組中解釋的那樣,您可以模擬getLog的LogFactory。
以下內容取自grails.tests.MockUtils.mockLogging並進行修改以返回記錄器。
class LoggingEnabledTestCase extends GrailsUnitTestCase {
protected void setUp() {
super.setUp()
registerMetaClass(org.apache.commons.logging.LogFactory)
org.apache.commons.logging.LogFactory.metaClass.'static'.getLog = {instance ->
// This is taken from grails.tests.MockUtils and slightly changed to return a logger.
// Get the name of the class + the last component of the package
// (if it the class is in a package).
def pos = instance.class.name.lastIndexOf('.')
if (pos != -1) pos = instance.class.name.lastIndexOf('.', pos - 1)
def shortName = instance.class.name.substring(pos + 1)
// Dynamically inject a mock logger that simply prints the
// log message (and optional exception) to stdout.
def mockLogger = [
fatal: {String msg, Throwable t = null ->
println "FATAL (${shortName}): $msg"
if (t) {
println " Exception thrown - ${t.message}"
}
},
error: {String msg, Throwable t = null ->
println "ERROR (${shortName}): $msg"
if (t) {
println " Exception thrown - ${t.message}"
}
},
warn: {String msg, Throwable t = null ->
println "WARN (${shortName}): $msg"
if (t) {
println " Exception thrown - ${t.message}"
}
},
info: {String msg, Throwable t = null ->
println "INFO (${shortName}): $msg"
if (t) {
println " Exception thrown - ${t.message}"
}
},
debug: {String msg, Throwable t = null ->
println "DEBUG (${shortName}): $msg"
if (t) {
println " Exception thrown - ${t.message}"
}
},
trace: {String msg, Throwable t = null -> },
isFatalEnabled: {-> true},
isErrorEnabled: {-> true},
isWarnEnabled: {-> true},
isInfoEnabled: {-> true},
isDebugEnabled: {-> true},
isTraceEnabled: {-> false}] as Log
return mockLogger
}
}
protected void tearDown() {
super.tearDown()
}
}
那麼如何測試一個充滿日誌語句的控制器呢?我現在有這個問題? – 2009-12-17 02:54:02
在測試的setUp()方法中使用mockLogging(MyDamnCoolCOntroller,true)。 – 2009-12-17 13:18:55