Last active
December 12, 2015 08:39
-
-
Save Igosuki/4745968 to your computer and use it in GitHub Desktop.
Grails logging mocking
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment