Search code examples
c#wcfunit-testingwcf-data-servicesnsubstitute

c# WCF Testing EntityDescriptor


I have a WCF client where I get data via OData. I want to unit test my client and already made an interface for the DataServiceContext:

internal interface ODataServiceContext
{

    DataServiceResponse SaveChanges(SaveChangesOptions options);

    ReadOnlyCollection<LinkDescriptor> Links { get; }

    ...

}

For my test currently I need to fake the Links property. I need to return at least one LinkDescriptor. Does anybody has an idea how to achieve this?

For now I use NSubstitute for faking the interface:

var context = Substitute.For<ODataServiceContext>();
var list = new List<LinkDescriptor>();
var links = new ReadOnlyCollection<LinkDescriptor>(list);
context.Links.Returns(links);

This works for testing against an empty Linksproperty. But how can I achive to add a link descriptor to the collection as the class LinkDescriptor does not have a public constructor and is sealed?


Solution

  • Finally I did it via reflection calling the non public constructor of the LinkDescriptorclass:

    var constructors = typeof(LinkDescriptor).GetConstructors(System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
    var descriptor = constructors[1].Invoke(new object[] { null, propertyName, null, entityState }) as LinkDescriptor;
    

    It seems, that the four parameter for the constructor are:

    • object source: Source entity
    • string sourceProperty: Navigation property on the source entity
    • object target: Target entity
    • EntityStates state: State of the link