Mocking generics that implement multiple interfaces - c#

Here's my class implementation where the generic is implementing two interfaces...
public class ClassA<TGeneric> : where TGeneric: IInterfaceA, IInterfaceB
I want to Mock ClassA. However, I can't use
var mock = new Mock<Class<A<IInterfaceA>>();
or
var mock = new Mock<Class<A<IInterfaceB>>();
since the generic requires implementations of both interfaces. I know you can mock objects with multiple interfaces by using the As() method on the moq, but I don't really have an object here but a generic type.
Thoughts?
Thanks...

You could define an interface that includes both interface A and B (in your test project, for testing purposes), then use that in your mock.
public interface ICanTestAAndB : IInterfaceA, IInterfaceB {}
var mock = new Mock<ClassA<ICanTestAAndB>>();

As alternative to the accepted answer you can achieve what you need by casting the mocked object to dynamic and at runtime it will work as expected.
void Main()
{
var mockA = new Mock<IIntA>();
mockA.Setup(a => a.DoA()).Returns(3);
var mockB = mockA.As<IIntB>();
mockB.Setup(iib => iib.DoB()).Returns(7);
dynamic d = mockB.Object;
TakeBoth(d);
}
void TakeBoth<T>(T obj) where T : IIntA, IIntB
{
}
public interface IIntA { int DoA(); }
public interface IIntB { int DoB(); }

Related

Moq - How to create a mock that implements multiple interfaces at the same time [duplicate]

Here's my class implementation where the generic is implementing two interfaces...
public class ClassA<TGeneric> : where TGeneric: IInterfaceA, IInterfaceB
I want to Mock ClassA. However, I can't use
var mock = new Mock<Class<A<IInterfaceA>>();
or
var mock = new Mock<Class<A<IInterfaceB>>();
since the generic requires implementations of both interfaces. I know you can mock objects with multiple interfaces by using the As() method on the moq, but I don't really have an object here but a generic type.
Thoughts?
Thanks...
You could define an interface that includes both interface A and B (in your test project, for testing purposes), then use that in your mock.
public interface ICanTestAAndB : IInterfaceA, IInterfaceB {}
var mock = new Mock<ClassA<ICanTestAAndB>>();
As alternative to the accepted answer you can achieve what you need by casting the mocked object to dynamic and at runtime it will work as expected.
void Main()
{
var mockA = new Mock<IIntA>();
mockA.Setup(a => a.DoA()).Returns(3);
var mockB = mockA.As<IIntB>();
mockB.Setup(iib => iib.DoB()).Returns(7);
dynamic d = mockB.Object;
TakeBoth(d);
}
void TakeBoth<T>(T obj) where T : IIntA, IIntB
{
}
public interface IIntA { int DoA(); }
public interface IIntB { int DoB(); }

C# Multiple Stub implementation for method with T

Currently I have a factory class where I have method to instantiate different classes using reflection and return a base interface which all classes implement. The code works fine in general. But when I turned to write unit test (ms-test) on the class I'm running into issues when I try to instantiate multiple classes
Factory class:
public class BusinessFactory : IBusinessFactory
{
public BusinessFactory()
{
}
public IBaseBusiness Create<T>() where T : class
{
return (IBaseBusiness) Activator.CreateInstance(typeof(T));
}
}
Unit test:
I tried to stub the IBusinessFactory and inject into my class under test so I can fake the implementations that the class uses.
Example: failing to complete TestInit method, and it's failing when instantiating stub of class2.
interface IClass1 : IBaseBusiness{}
public Class1 : IClass1{}
interface IClass2 : IBaseBusiness{}
public Class2 : IClass2{}
public TestFactory{
[TestInitialize]
public void TestInit()
{
var fkBusFac = new StubIBusinessFactory();
fkBusFac.CreateOf1<Class1>(() => new StubIClass1() { });
fkBusFac.CreateOf1<Class2>(() => new StubIClass2() { });
}
Can anyone please help?
Not an answer to your question, but...
What happens if I do the following?:
var business = Create<string>();
You have absolutely no type safety at all here. If the created object implements IBaseBusiness, ensure it does and simply call new() (oh, and if its a factory method, shouldn't you be making it static?):
public static IBaseBusiness Create<T>() where T : IBaseBunsiness, new()
{
return new T();
}

rhino mock an interface IA which implements interface IB with abstract class aB

I have a situation where I have in interface
public interface IA : IB
{
}
where
public interface IB
{
List<string> Errors{get;}
void AddError(string error);
}
with an abstract class
public abstract class B
{
private List<string> errors = new List<string>();
public List<string> Errors{get{return errors;}}
public void AddError(string error)
{
if (!errors.Contains(error))
errors.Add(error);
}
}
And I have a method on another class like:
public class MyClass
{
public void MyMethod(IA obj)
{
obj.AddError("some string");
}
}
then I have a unit test where I would like to test that MyClass does what it is supposed to by passing in a stubbed IA:
public void Test()
{
var sut = new MyClass();
var input = MockRepository.GenerateStub<IA>();
sut.MyMethod(input);
Assert.AreEqual(1, input.Errors.Count);
}
but when it comes to the assertion, Errors is null as the base class B is not included in the stub for IA, is there any way to specify that I want the implementation of IB to be provided by an abtsract class without having to create a concrete class that derives from B?
I have missed some of the detail from this, but I will expand by saying that there are a set of interfaces like IA all implementing IB, and a set of classes like MyClass each taking a different interface and the detail of MyMethod depends on the interface IA that it accepts, but the interfaction with the implementation of IB is always the same.
One possible solution is to create an abstract implementation of IA
public abstract class A : B, IA
{
//abstract implementations of all properties and methods on IA, nothing concrete
}
this can then be stubbed in the unit test:
public void Test()
{
var sut = new MyClass();
var input = MockRepository.GenerateStub<A>();
sut.MyMethod(input);
Assert.AreEqual(1, input.Errors.Count);
}
and the propertis and methods on A that need to be stubbed (or mocked) can than be done.
It does mean that an additional class nedds to be wiritten fr each interface that exists in the vein of IA, whic is far from ideal, but its the nly way I see around this for now.
Interface stands for behavioral contract. It is by its nature not coupled with any implementation. What you want is a mock-ed object who carries behavior defined by class B (in other words you need a mocked B object), and at the same time implements IA.
You could use multi, partial mock to achieve it:
var sut = new MyClass();
var input = MockRepository.GeneratePartialMock<B, IA>();
sut.MyMethod((IA)input);
Assert.AreEqual(1, input.Errors.Count);
GeneratePartialMock is the method to mock a class who already has some behavior defined. Basically it gives you the capability to rewrite(stub) override-able methods defined in a class. And if you don't stub a method, the original behavior will be invoked.
You can include more interfaces (in your case, IA) in the type parameter list to dynamically add behavior to your mock-ed object.
Note you have to revise the code you posted in order to make it work:
Initialize () should be defined in the interface IB
Methods should be defined as virtual in class B

Generic WeakReference proxy

I want to create custom WeakReference<T> which would implement an interface passed as generic parameter T.
Usage:
interface IInterface
{
void SomeMethod(bool param);
}
public class Subject : IInterface { /*...*/ }
var proxyRef = new ProxyWeakReference<IInterface>(new Subject());
proxyRef.SomeMethod(false);
IInterface subject = proxyRef.Target;
Is there any already created solutions to do that? Or what i should use to create such type of proxy?
Probably, You are looking for a Moq

What is the nicest way to dynamically implement an interface in C#?

I often find it quite a distraction to have to implement an interface just because I need it once for some method call. I have to create a class somewhere else, implement the interface etc. etc.
Java has a feature called Anonymous Classes that allows one to implement the interface "inline". My question is thus: what is the nicest way you can think of of accomplishing something similar in C# using existing syntax (and I realise that "nicest" is subjective). I'm looking for nice syntax, not necessarily performance.
I implemented the following as POC in C#:
Given
interface IFoobar
{
Boolean Foobar(String s);
}
IFoobar foo = Implement.Interface<IFoobar>(new {
Foobar = new Func<String, Boolean>(s => s == "foobar")
});
This uses an anonymous object and some reflection/emit to implement the IFoobar interface (overlooking properties, generic methods and overloading). But, I'm not a fan of the new Func<...> stuff but can't do without.
Looking around I noticed a library called Impromptu Interface, but wasn't impressed by its syntax to support methods.
Is there a "nicer" way?
Edit: I'm not looking for Java vs C# flame wars.
You mentioned that you didn't need to do this often, don't care about performance, and usually want to do it during unit testing. Why not use a mocking framework?
For example, using the Moq library as an example:
public interface IFoobar {
Boolean Foobar(String s);
}
void Main() {
var foo = new Mock<IFoobar>();
foo.Setup(x => x.Foobar(It.IsAny<string>()))
.Returns((string s) => s == "foobar");
foo.Object.Foobar("notbar"); // false
foo.Object.Foobar("foobar"); // true
}
Take a look at "impromptu-interface" (https://github.com/ekonbenefits/impromptu-interface).
It will allow you to do something like...
class Program
{
static void Main(string[] args)
{
Bar b = new Bar();
b.DoSomethingWithFoo(new
{
Foobar = Return<string>.Arguments<string>(r => "foo")
}.ActLike<IFoo>());
}
}
public interface IFoo
{
string Foobar(String s);
}
public class Bar
{
public void DoSomethingWithFoo(IFoo foo)
{
Console.WriteLine(foo.Foobar("Hello World"));
}
}
A good way to do what you need in C# could be using Clay objects:
public interface IFoobar{
Func<string, bool> Foobar { get; set; }
}
With that interface you can do something like this:
dynamic New = new ClayFactory();
var foobar= New.FooBar();
foobar.Foobar = new Func<string, bool>(s => s == "foobar");
// Concrete interface implementation gets magically created!
IFoobar lou = foobar;
var result =lou.Foobar("foo");// return false
What makes the magic possible is that Clay is overriding the cast operator and creating a dynamic proxy for the interface (using Castle) that delegates the members to the Clay object.
Another way could be using the Impromptu Interface library which lets you wrap any object with an interface. That means any objects now can have dynamic behaviors. If an object has interface methods, you can directly attach behaviors to them as needed. If an object does not have interface methods, you define an interface and wrap the object in it, then, attach behaviors to the interface methods as needed.This library is an automatic way of applying the Object Adapter pattern.
If you have an interface like this:
public Interface IFoobar
{
bool Foobar(string s);
}
You can decorate an anonymous type as I show below:
//Anonymous Class
var anon = new {Foobar= Return<bool>.Arguments<string>(s => s == "foobar")};
var myInterface = anon.ActLike<IFoobar>();
Or you could use an ExpandoObject too:
dynamic expando = Build<ExpandoObject>.NewObject(Foobar: Return<bool>.Arguments<string>(s => s == "foobar"));
IMyInterface myInterface = Impromptu.ActLike(expando);
If you want to implement more than one interface, check my answer in this post.
public class Foo
{
public Func<string,bool> TheDelegate {get;set;}
}
public class Bar
{
public bool Implementation(string s)
{
return s == "True";
}
}
public class Usage
{
var myBar = new Bar();
var myFoo = new Foo { TheDelegate = myBar.Implementation };
//Or
var myFoo = new Foo { TheDelegate = x => x == "True" };
//This removes the need for Bar completely
}
As you can see in the above example, java-like hacks are completely unneeded in C#, which is a much better language.
It is possible to do a cleaner lambda syntax, however at the expense of static type checking inside Create().
I was able to use ImpromptuInterface to do this:
IFoobar foo = Implement.Interface(new {
Foobar = Function.Create(s => s == "foobar"),
});
By creating the following classes:
public static class Implement{
public static dynamic Interface(object source){
return Impromptu.ActLike(source);
}
}
public static class Function{
public static Func<dynamic> Create(Func<dynamic> del){
return del;
}
public static Func<dynamic,dynamic> Create(Func<dynamic,dynamic> del){
return del;
}
public static Func<dynamic,dynamic,dynamic> Create(Func<dynamic,dynamic, dynamic> del){
return del;
}
public static Func<dynamic,dynamic,dynamic,dynamic> Create(Func<dynamic,dynamic, dynamic,dynamic> del){
return del;
}
//...Add more if you want
}
Unfortunately anonymous classes in C# canĀ“t implement interfaces as in Java. However you can create some kind of adapter-class without any additional dependencies on external projects. Just create a base-class that implements your interface using a Func:
interface IFoo
{
bool DoSomething(string value);
}
class Bar : IFoo
{
private readonly Func<string, bool> m_DoSomething;
public Bar(Func<string, bool> DoSomething) { this.m_DoSomething = DoSomething; }
public bool DoSomething(string value)
{
return this.m_DoSomething(value);
}
}
Now you can call it like this:
var result = new Bar(x => true);
Or also using named arguments which is bit more obvious, in particular if your interface has more then one method:
var result = new Bar(DoSomething: x => true);
Only drawback is that you need an implementing class for every interface you have. Thus this approach is only usefull if you want to implement every interface more than once with different behaviour. So whenever I need different implementations for the same interface I use this approach.
If your biggest complaint is implementing the interface somewhere else, why not create a nested class directly before/after your method? (Compare to a Java static nested class.)
That's more idiomatic C# than creating/using some dynamic framework.

Categories

Resources