Java Reference
In-Depth Information
Listing 6.13. A test for the addition script, calc.groovy
void testAddition() {
def result = withBinding( [x:3,y:4] ) {
shell.evaluate(new File('src/main/groovy/mjg/calc.groovy'))
shell.context.z
}
assert 7 == result
}
The last line of the closure accesses the z variable, whose value is retrieved from the bind-
ing.
There's one other subclass of GroovyTestCase available in the standard library, called
GroovyLogTestCase , which helps when testing logging. That class is the subject of
the next subsection.
6.2.2. Useful subclasses of GroovyTestCase: GroovyLogTestCase
Good developers don't rely on capturing standard output. Instead they use loggers to direct
output to locations that can be accessed later. For some time now Java has had a basic log-
gingcapability built into it, which can act as the frontendonlogging APIimplementations.
The Java logging classes, like Logger and Level , reside in the java.util.logging
package. As an example of their use, consider the following minor variation on the cal-
culator script from the previous section, stored in a file called calc_with_ log-
ger.groovy .
Listing 6.14. A script that uses a logger
import java.util.logging.Logger
Logger log = Logger. getLogger (this.class.name)
log.info("Received (x,y) = ($x,$y)")
z = x + y
The static getLogger method from the Logger class is a factory method that creates
a Logger instance for this particular component. Here I'm using the name of the script,
which becomes the name of the generated class. Once again, the variables x , y , and z are
part ofthe script binding. The logger provides methods corresponding tovarious loglevels.
Search WWH ::




Custom Search