使用Rhino Mocks对存储库对象进行Stubbing函数表达

时间:2017-03-13 09:58:57

标签: c# mocking rhino-mocks

我使用Rhino Mocks对一个服务方法进行单元测试,该方法进行以下调用:

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

Repo.GetOne方法签名是:

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

到目前为止,我只是通过忽略Function Expression参数来实现这一目的:

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

当使用参数f => f.Id == formId, "FormTemplate, Event"调用方法时,如何存根Repo.GetOne方法以设置返回值?

1 个答案:

答案 0 :(得分:2)

设置Stub / Mocks时,当您调用mockArg.Equals(runtimeArg)时,参数使用的值必须返回true。您的Func<>不会这样做,所以您最好选择使用Arg<T>.Matches()约束,该约束采用的函数在给定存根输入时返回true,如果运行时输入是匹配。

不幸的是,查看Func<T>代表的内容并不简单。 (看看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);
相关问题