Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create fake object by interface

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?

like image 214
Lukas Pirkl Avatar asked Feb 17 '12 15:02

Lukas Pirkl


People also ask

How do I create a fake object in Java?

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).

How do I create a fake object or delegate?

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:

How do I create a fake object in Swift?

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>>();

How do I create a fake class in Visual Studio?

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.


3 Answers

You could use a mocking API such as Moq. It's designed for mocking in unit tests, but it should do what you need.

like image 81
jrummell Avatar answered Sep 30 '22 04:09

jrummell


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>();
like image 20
brgerner Avatar answered Sep 30 '22 06:09

brgerner


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.

like image 23
RichK Avatar answered Sep 30 '22 05:09

RichK