0

I'm using Rhino Mocks to unit test a service method that makes the following call:

var form = Repo.GetOne<Form>(f => f.Id == formId, "FormTemplate, Event");

The Repo.GetOne method signature is:

TEntity GetOne<TEntity>(
            Expression<Func<TEntity, bool>> filter = null,
            string includeProperties = null)
            where TEntity : class, IEntity;

So far I have only managed to do this by ignoring the Function Expression argument:

_mockRepo.Stub(
    r => 
    r.GetOne<Form>(                    
      Arg<Expression<Func<Form, bool>>>.Is.Anything,
      Arg<string>.Is.Equal("FormTemplate, Event")))
    .Return(form);

How do I stub the Repo.GetOne method in order to set the return value when the method is called with arguments f => f.Id == formId, "FormTemplate, Event"?

TonE
  • 2,975
  • 5
  • 30
  • 50

1 Answers1

2

When you setup Stub/Mocks, the value used for the arguments must return true when you call mockArg.Equals(runtimeArg). Your Func<> isn't going to do that, so you're best bet is to use the Arg<T>.Matches() constraint, which takes a function that, given the stub inputs, returns true if the runtime input are a match.

Unfortunately, looking at the contents of the Func<T> delegate is not straightforward. (Take a look at https://stackoverflow.com/a/17673890/682840)

  var myArgChecker = new Function<Expression<Func<Form, bool>>, bool>(input =>
        {
            //inspect input to determine if it's a match
            return true; //or false if you don't want to apply this stub                    
        });


_mockRepo.Stub(
    r => 
    r.GetOne<Form>(                    
      Arg<Expression<Func<Form, bool>>>.Matches(input => myArgChecker(input)),
      Arg<string>.Is.Equal("FormTemplate, Event")))
    .Return(form);
Community
  • 1
  • 1
John M. Wright
  • 4,477
  • 1
  • 43
  • 61
  • Thanks, this really helped. I ended up with a solution by combining this approach with the expression equality checker in this SO post: http://stackoverflow.com/a/24528357/95423 – TonE Mar 30 '17 at 15:21