0

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?

Caffeinated Coder
  • 670
  • 1
  • 8
  • 24
  • Your question is unclear. Apparently, you generate code and you use that code. So what’s the obstacle when testing the code, i.e. like any other code? What do you mean with “*ensure that these instances were indeed created in runtime*”? Normally, you notice whether it happened or not. If you don’t notice, what’s the point of ensuring that something happens, that has no effect? The testing strategy should focus on the desired result, e.g. produced side effect, not on technical details like whether an instantiation happened. – Holger Mar 09 '17 at 11:25
  • What I meant by the question was a way to ensure that objects were indeed generated in runtime. Rafael's answer is what I was looking for. – Caffeinated Coder Apr 11 '17 at 14:11

1 Answers1

1

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.

Rafael Winterhalter
  • 42,759
  • 13
  • 108
  • 192