c# - 你如何用 Rhino Mocks stub IQueryable<T>.Where(Func<T, bool>)?

标签 c# unit-testing nunit rhino-mocks iqueryable

在我目前从事的 .net 3.5 项目中,我正在为一个服务类编写一些测试。

public class ServiceClass : IServiceClass
{
     private readonly IRepository _repository;

     public ServiceClass(IRepository repository)
     {
          _repository = repository;
     }

     #region IServiceClass Members

     public IEnumerable<ActionType> GetAvailableActions()
     {
         IQueryable<ActionType> actionTypeQuery = _repository.Query<ActionType>();
         return actionTypeQuery.Where(x => x.Name == "debug").AsEnumerable();
     }

     #endregion
}

我很难弄清楚如何 stub 或模拟

actionTypeQuery.Where(x => x.Name == "debug")

部分。

这是我到目前为止得到的:

[TestFixture]
public class ServiceClassTester
{
    private ServiceClass _service;
    private IRepository _repository;
    private IQueryable<ActionType> _actionQuery;
    [SetUp]
    public void SetUp()
    {
        _repository = MockRepository.GenerateMock<IRepository>();
        _service = new ServiceClass(_repository);
    }

    [Test]
    public void heres_a_test()
    {
        _actionQuery = MockRepository.GenerateStub<IQueryable<ActionType>>();

        _repository.Expect(x => x.Query<ActionType>()).Return(_actionQuery);
        _actionQuery.Expect(x => x.Where(y => y.Name == "debug")).Return(_actionQuery);

        _service.GetAvailableActions();

        _repository.VerifyAllExpectations();
        _actionQuery.VerifyAllExpectations();
    }

}

[注意:类名已更改以保护无辜者]

但这失败了,出现了 System.NullReferenceException at

_actionQuery.Expect(x => x.Where(y => y.Name == "debug")).Return(_actionQuery);

所以我的问题是:

如何使用 RhinoMocks 模拟或 stub IQueryable.Where 函数并让此测试通过?

如果我当前的设置不允许我模拟或 stub IQueryable,请给出合理的解释。

感谢阅读这个冗长的问题。

最佳答案

在不使用 Rhino 模拟的情况下,您可以创建一个列表,然后在其上调用 .AsQueryable()。例如

var actionTypeList = new List<ActionType>() {
    new ActionType {},  //put your fake data here
    new ActionType {}
};

var actionTypeRepo = actionTypeList.AsQueryable();

这至少会给你一个假的存储库,但它不会让你验证是否调用了方法。

关于c# - 你如何用 Rhino Mocks stub IQueryable<T>.Where(Func<T, bool>)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/791256/

相关文章:

c# - 无论如何使用 asp.net mvc 从 3 个图像 URL 中制作一个图像?

asp.net-mvc - 测试 Asp.net MVC 应用程序的最佳实践

c# - 执行 javascript 时,Watin 集成测试因 System.UnauthorizedAccessException 而失败

c# - 如何迭代运行 nunit 测试

c# - 暂停线程直到 WebBrowser 完成加载

c# - 脚本# 包装 WebGL?

c# - Nhibernate .Fetch 调用在模拟 session 中失败

java - 验证是否从构造函数调用了方法

c# - 使用事件和委托(delegate)对类进行单元测试

c# - Visual Studio 项模板 : Replace with project name