Reputation: 1
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.
Upvotes: 0
Views: 781
Reputation: 44032
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.
Upvotes: 1