Reputation: 10063
I am the customer of a library generating objects of class C
which implements two interfaces IA
and IB
, which represents a permanent connection which I need to store.
I need to store the object C
returned between calls.
class Example
{
C _obj;
}
I would like to mock the interface functions used by C
for testing, but because 'C' inherits multiple interface I do not have an interface IC
, so I cannot write:
class Example
{
Example(IC cInstance) { _obj = cInstance; }
IC _obj;
}
therefore I cannot create easily a mock object that would implement both interfaces IA
and IB
which I could use for testing that my class Example
works.
How do I do this without using casting or something ugly ?
Upvotes: 2
Views: 728
Reputation: 2965
If the object inherits two interfaces, probably should you store two references:
class Example
{
Example(IA aInstance, IB bInstance) { _a = aInstance; _b = bInstance; }
IA _a;
IB _b;
}
And that's not ugly. On the contrary.
Upvotes: 3
Reputation: 7773
You can do it using generics:
class Example<T> where T : IA, IB
{
public Example(T instance)
{
this.obj = instance;
}
private T obj;
}
You can use C
or your mockup with Example
as long as that class implements both interfaces:
class CMock : IA, IB
{
// ...
}
var myMockObj = new CMock();
var example = new Example<CMock>(myMockObj);
Upvotes: 5