0
votes

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"?

1

1 Answers

2
votes

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);