Search code examples
javajava-bytecode-asmbyte-buddy

How to validate and write test cases to check ASM/Byte Buddy instances were created in runtime


I have code written in ASM and Byte Buddy and I need to write test cases to ensure that these instances were indeed created in runtime.

Any ideas about how should one go about it?


Solution

  • I assume that you are asking how to validate generated classes. As an inspiration, have a look at Byte Buddy's tests which do of course test generated code. A simple test can look like this:

     Class<?> type = new ByteBuddy()
         .makeInterface()
         .make()
         .load(getClass().getClassLoader(), ClassLoadingStrategy.Default.WRAPPER)
         .getLoaded();
    assertThat(Modifier.isPublic(type.getModifiers()), is(true));
    assertThat(type.isEnum(), is(false));
    assertThat(type.isInterface(), is(true));
    assertThat(type.isAnnotation(), is(false));
    

    The above test validates the creation of an interface. Using the reflection API, you can interact with the generated class after its creation.

    Byte Buddy offers the ClassLoadingStrategy.Default.WRAPPER strategy for isolating the generated code. This way, Byte Buddy generated a new class loader for the class and the unit tests remain repeatable. This would not be the case if a class was loaded into an existing class loader like the system class loader.