【问题标题】:Rhino Mocks - Testing Repository layer returns "object reference not set to instance" errorRhino Mocks - 测试存储库层返回“对象引用未设置为实例”错误
【发布时间】:2011-11-15 02:15:09
【问题描述】:

我首先说我对 Rhino Mocks 和更一般的 mocking 都是新手。

考虑到这一点,我正在尝试对我的 Linq to SQL 存储库层进行单元测试,以确保命中数据上下文中的正确方法,并且 LINQ to SQL 正在正确过滤。

~为清楚起见已编辑~

有问题的方法 - 'GetRecordWhere' - 在 Repository 类中定义。 它在 DataContextWrapper 上调用方法 - 'GetTable' - 这是我围绕 Linq to SQL DataContext(自动生成)的自定义包装器,它被实施以使 DataContext 可模拟。

public interface IDataContextWrapper : IDisposable
{
    IQueryable<TName> GetTable<TName>() where TName : class;
}

public class DataContextWrapper : IDataContextWrapper
{
    public IQueryable<TName> GetTable<TName>() where TName : class
    {
        return _db.GetTable<TName>().AsQueryable();
    }
}

public class Repository :  IRepository
{
    public T GetRecordWhere<T>(Expression<Func<T, bool>> predicate) where T : class
    {
        return _dataContext.GetTable<T>().Where(predicate).SingleOrDefault();
    }
}

我当前遇到的错误是在尝试存根“GetTable”方法以提供可使用“GetRecordWhere”方法查询的可查询结果集时引发的。

ArgumentNullExcpetion: 值不能为空。参考线抛出:

Arg<Expression<Func<Billing, bool>>>.Is.Anything

.. 我也尝试过 Is.NotNull 和特定谓词。

单元测试示例:

    _dataContext = MockRepository.GenerateMock<IDataContextWrapper>();

    [Test]
    public void GetRecordWhere()
    {
        // Arrange
        var billing = new Billing { BillingId = 1 };
        var billingQueryList = new List<Billing> {billing};
        const int testId = 1;

       _dataContext.Stub(x => x.GetTable<Billing>()
                .Where(Arg<Expression<Func<Billing, bool>>>.Is.Anything)
                .SingleOrDefault())
                .Return(billing);

        _intRepository = new Repository(_dataContext);

        // Act
        var result = _intRepository.GetRecordWhere<Billing>(x => x.BillingId == testId);

        // Assert
        Assert.IsNotNull(result);
        Assert.AreEqual(result.BillingId, testId);
        _dataContext.AssertWasCalled(x => x.GetTable<Billing>());
    }

这是我对 RhinoMocks 理解的失败吗?

感谢您的帮助!

【问题讨论】:

  • 这个问题很长,现在有三个更新。您问题的原始部分提到获得 NullReferenceException。稍后您提到获得 ArgumentNullException。您能否重新编辑您的问题和代码,以提供仅包含相关部分的完整失败测试用例?
  • 用当前问题和代码解释更新了主帖

标签: c# linq-to-sql rhino-mocks


【解决方案1】:

您想用 Rhino.Mocks 模拟的任何方法都必须是虚拟的,这样 Rhino.Mocks 才能拦截它并提供您定义的存根/模拟行为。查看您对GetTable 的定义,它不是虚拟的,因此无法模拟。

更新:

不要“链接”您的方法模拟。只需定义您希望该方法执行的操作并返回值:

_dataContext.Stub(x => x.GetTable<Billing>()).Return(billingQueryList.AsQueryable());

我刚刚将您的示例代码插入到单元测试中,并且通过上述存根设置,测试通过了。

【讨论】:

  • 您能举个例子吗?我还使用定义 GetTable 的包含类实现的接口更新了我的问题。当我模拟这个方法时,我正在对模拟“datacontext”中包含的方法进行存根。如果这有意义的话......
猜你喜欢
  • 2019-05-01
  • 1970-01-01
  • 2013-08-18
  • 1970-01-01
  • 2020-03-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多