Daily Archives: November 24, 2022

Mockito – ByteBuddy Examples

ByteBuddy is key framework used in Mockito, it will auto generated subclass and override default methods. Following code will print out “Hello ByteBuddy!”.

import net.bytebuddy.ByteBuddy;
import net.bytebuddy.dynamic.DynamicType;
import net.bytebuddy.implementation.FixedValue;
import net.bytebuddy.matcher.ElementMatchers;

public class ByteBuddyEntry {
    public static void main(String[] args)
    {
        DynamicType.Unloaded unloadedType = new ByteBuddy()
                .subclass(Object.class)
                .method(ElementMatchers.isToString())
                .intercept(FixedValue.value("Hello ByteBuddy!"))
                .make();

        Class<?> dynamicType = unloadedType.load(ByteBuddyEntry.class
                        .getClassLoader())
                .getLoaded();

        try {
            System.out.println(dynamicType.newInstance().toString());
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }
}