jeudi 8 octobre 2015

Mock result from Func with NSubstitute

I'm trying to use NSubstitute to mock the return value from a Substitute, but I cannot get the substitute to return the correct value because the method signature is using a Func.

I've seen these questions, but cannot make it work with my Func.

Mocking Action<T> with NSubstitute

Mocking out expression with NSubstitute

The interface I try to mock is this (somewhat simplyfied):

public interface IOrgTreeRepository<out T> where T : IHierarchicalUnit
{
    T FirstOrDefault(Func<T, bool> predicate);
}

I'm substituting it with NSubstitute like so:

_orgTreeRepository = Substitute.For<IOrgTreeRepository<IOrganizationUnit>>();

And then I try to change the return value like so:

_orgTreeRepository.FirstOrDefault(Arg.Is<Func<IOrganizationUnit, bool>>(x => x.Id== _itemsToUpdate[0].Id)).Returns(existingItems[0]);

But it simply returns a proxy-object instead of my defined object in existingItems.

However, thanks to the other questions I managed to get this to work, but it does not help me, since I need a specific item every time.

_orgTreeRepository.FirstOrDefault(Arg.Any<Func<IOrganizationUnit, bool>>()).Returns(existingItems[0]); // Semi-working

I guess it's treating the lambda expression as a kind of absolute reference and therefore skips it? Is there any way I can mock the return value?

Aucun commentaire:

Enregistrer un commentaire