5. Who does this?
⢠About a million tutorials
â Usually print the class name
â At best adding simple trace code to methods
⢠Newer, cooler mocking frameworks
â Powermock, Mockito, JMockit
â Better approach then JMock & friends (which use
Proxy + CGLIB)
â Mock final classes/methods, plus other stuff
⢠Pure Java profilers?
8. How?
⢠Specify byteman.jar as a Java Agent when you
start your app
⢠Provide a Byteman rule script
⢠Can provide these scripts later (to a running
app) â app must be started with Byteman
listener
9. Simple program
package org.my
class AppMain
{
public static void main(String[] args)
{
for (int i = 0; i < args.length; i++) {
System.out.println(args[i]);
}
}
}
10. Run it
> java org.my.AppMain foo bar baz
foo
bar
baz
>
11. Byteman rule script
RULE trace main entry
CLASS AppMain
METHOD main
AT ENTRY
IF true
DO traceln("entering main")
ENDRULE
12. Byteman rule script
RULE trace main exit
CLASS AppMain
METHOD main
AT EXIT
IF true
DO traceln("exiting main")
ENDRULE
13. Run it
> java -
javaagent:byteman.jar=script:appmain.btm org.m
y.AppMain foo bar baz
entering main
foo
bar
baz
exiting main
>
14. Worth mentioning
⢠You can use it on classes you donât have the
source for
⢠You can even use this on core Java classes
(java.lang) â Byteman makes you confirm
⢠Works on interfaces too (all implementing classes
get your injected code)
⢠Much more sophisticated rule scripts
â Different âATâ points in method
â âIFâ statements that do something
â Access to local variables (eg âAFTER WRITE $fooâ)
16. Testing support
⢠Comes with a JUnit Runner
⢠Define the rules (from earlier scripts) as test
annotations
⢠Useful for fault injection (integration tests
where youâre not mocking everything out?)
17. Testing support
@Test
@BMRule(name=âfooâ,
targetClass = âFileInputStreamâ,
targetMethod=â<init>(File)â,
condition=â$1.getName().equals(âdoesnt_exist.txtâ)â,
action=âthrow new FileNotFoundException(âItâs not there!â)â)
public void testReadFile() {
...
myClass.processFile(âdoesnt_exist.txtâ); // Throws an exception
...
}
18. Testing support
⢠Rule in previous example will only be in place
for that test
â Can annotate class instead to apply to all tests
⢠Thereâs also @BMScript to import external
rule scripts
⢠Relatively simple to run with maven (config
samples on website)
19. Summary
⢠Seems cool
⢠Not sure what Iâd actually use it for
⢠Integration tests most likely candidate