vendredi 15 avril 2016

C# Reflection - how to get interface to pass to a generic method?

For unit testing, I am using RhinoMock and in the example below you can see that I successfully create a Stub based on the interface ISomething:

var stub = MockRepository.GenerateStub<ISomething>();

All well and good.

However, I'm writing a test which loops through the properties of an object using Reflection and I then want to dynamically create a stub based on the current property.

So, imagine that my class under test is Parent:

public class Parent
{
    public ISomething Prop1 {get;set;}
    public ISomethingElse Prop2 {get;set;}
    public ISomethingEntirelyDifferent Prop3 {get;set;}
}

With Reflection I can get the individual properties using:

typeof(parent).GetProperties(BindingFlags.Public | BindingFlags.Instance)

And when I iterate through each property, I see the name of the Interface (ISomething, ISomethingElse, ISomethingEntirelyDifferent) on the current property using:

p.PropertyType.Name

But I'm not sure how to then plug that into:

var stub = MockRepository.GenerateStub<????>();





Aucun commentaire:

Enregistrer un commentaire