I need to dynamically create fake object by interface. Every method and property of this fake object should just throw NotImplementedException. Is there any simple way how to do it only with .NET reflection API?
The common way to create a fake object is by using the A.Fake syntax, for example: This will return a faked object that is an actual instance of the type specified ( IFoo in this case).
The common way to create a fake object is by using the A.Fake syntax, for example: This will return a faked object that is an actual instance of the type specified ( IFoo in this case). You can create a fake delegate with the same syntax: You can also create a collection of fakes by writing:
The common way to create a fake object is by using the A.Fake syntax, for example: var foo = A.Fake<IFoo>(); This will return a faked object that is an actual instance of the type specified (IFoo in this case). You can create a fake delegate with the same syntax: var func = A.Fake<Func<string, int>>();
To create a fake, create a class that inherits from an interface. Then, on Visual Studio, from “Quick Refactorings” menu, choose “Implement interface” option. Et voilà! You have your own fake. But, if you need to create lots of fake collaborators, a mocking library can make things easier.
You could use a mocking API such as Moq. It's designed for mocking in unit tests, but it should do what you need.
Maybe ImpromptuInterface can help.
A sample code (copied from its homepage) is:
using ImpromptuInterface;
using ImpromptuInterface.Dynamic;
public interface IMyInterface{
string Prop1 { get; }
long Prop2 { get; }
Guid Prop3 { get; }
bool Meth1(int x);
}
//Anonymous Class
var anon = new {
Prop1 = "Test",
Prop2 = 42L,
Prop3 = Guid.NewGuid(),
Meth1 = Return<bool>.Arguments<int>(it => it > 5)
}
IMyInterface myInterface = anon.ActLike<IMyInterface>();
Castle Proxies is a neat library that generates proxy objects for interfaces at run time. All the major mocking frameworks use Castle Proxies under the hood too.
The learning curve is steeper than using something like Moq, but it may be a more appropriate fit for your needs as Moq is designed to be used specifically for unit testing so the API may be too 'noisy' for what you're after.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With