0

I am trying to create proxy object using Byte Buddy. I actually want to mock any dependencies in any class and if any method is called on that depended object it will return a per-determined value to the caller.

public class Person{
 private String name;
 private Address address;

 public Person(String name, Address address){
     this.name = name;
     this.address = address;
 }
 public String getAddress(){
  return (address == null) "" : address.getStreet();
 }
}

=======================================================================

public class Address {
  private String street;
  public String getStreet() { return street; }

In this above example I want to mock Address in Person class and whenever person.getAddress() method is invoked. I want to dynamically return a value based on return type. I am new to Byte Buddy. I am able to create a subclass but not sure how to get dynamically return type of the method and return my per-determined value.

1 Answer 1

1

Do you have a chance to inject the value provided to the constructor? In this case, you can just create a subclass for Address:

Address address = new ByteBuddy()
  .subclass(Address.class)
  .method(any()).intercept(MethodDelegation.to(MyInterceptor.class))
  .make()
  .load(Address.class.getClassLoader())
  .getLoaded()
  .newInstance();

with a delegate similar to:

public class MyInterceptor {
  @RuntimeType
  public static Object intercept(@Origin Method method) {
    // create some return value or null for void
  }
}

Simply supply this object to the constructor.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your response. It worked for me, I found that in git hub wiki you similar examples and explanation. I need to invest some more time to byte buddy.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.