@Test(expected = IllegalStateException.class) public void testMissingInstrumentationThrowsException() throws Exception { Field field = ByteBuddyAgent.Installer.class.getDeclaredField(INSTRUMENTATION); field.setAccessible(true); field.set(STATIC_FIELD, null); ByteBuddyAgent.getInstrumentation(); }
@Test public void testInstrumentationExtraction() throws Exception { Field field = ByteBuddyAgent.Installer.class.getDeclaredField(INSTRUMENTATION); field.setAccessible(true); Instrumentation instrumentation = mock(Instrumentation.class); field.set(STATIC_FIELD, instrumentation); assertThat(ByteBuddyAgent.getInstrumentation(), is(instrumentation)); }
@Test @ToolsJarRule.Enforce public void testAgentSelfInitializationAuxiliaryTypes() throws Exception { assertThat(ByteBuddyAgent.installOnOpenJDK(), instanceOf(Instrumentation.class)); ClassFileTransformer classFileTransformer = new AgentBuilder.Default() .rebase(isAnnotatedWith(ShouldRebase.class), ElementMatchers.is(classLoader)) .transform(new QuxTransformer()) .installOnByteBuddyAgent(); try { Class<?> type = classLoader.loadClass(Qux.class.getName()); assertThat(type.getDeclaredMethod(FOO).invoke(type.newInstance()), is((Object) (FOO + BAR))); } finally { ByteBuddyAgent.getInstrumentation().removeTransformer(classFileTransformer); } }
@Test @ToolsJarRule.Enforce public void testAgentWithoutSelfInitializationWithNativeMethodPrefix() throws Exception { assertThat(ByteBuddyAgent.installOnOpenJDK(), instanceOf(Instrumentation.class)); ClassFileTransformer classFileTransformer = new AgentBuilder.Default() .disableSelfInitialization() .withNativeMethodPrefix(QUX) .rebase(isAnnotatedWith(ShouldRebase.class), ElementMatchers.is(classLoader)) .transform(new FooTransformer()) .installOnByteBuddyAgent(); try { Class<?> type = classLoader.loadClass(Baz.class.getName()); assertThat(type.getDeclaredMethod(FOO).invoke(type.newInstance()), is((Object) BAR)); assertThat(type.getDeclaredMethod(QUX + FOO), notNullValue(Method.class)); } finally { ByteBuddyAgent.getInstrumentation().removeTransformer(classFileTransformer); } }