Search code examples
c#fakeiteasy

FakeItEasy: faking return value when anonymous type is returned


I have a function:

TResult ShowDialogWindow<TViewModel, TView, TResult>(Func<TViewModel> viewModelActivator,
            Func<TViewModel, TView> viewActivator,
            Func<TViewModel, TView, TResult> dialogResultFunc)

I would like to fake the return value of the function except the code returns an anonymous type like so:

_dialogService.ShowDialogWindow(() => new ViewModel(),
  viewModel =>  new View(viewModel),
  (viewModel, view) => new { view.DialogResult, view.SomeOtherInfo });

I have looked at some pre-existing answers and discussions but they deal with matching parameters rather than return type:

Any suggestions?

P.S. My current workaround is to just avoid returning anonymous types.


Solution

  • Unfortunately, there's no easy way to do that. Anonymous types are defined per assembly; in other words, if you define an anonymous type in your test assembly that is identical to the one in your assembly under test, it won't actually be the same type.

    You might be able to do something with A.CallTo(dialogService).Where(call => ...), but it's going to be painful, as you'll have to give up strong typing and use reflection instead.

    Your best bet is to not use anonymous types; tuples and records are a good lightweight alternative.