gpt4 book ai didi

c# - Rhino Mocks - 测试存储库层返回 "object reference not set to instance"错误

转载 作者:行者123 更新时间:2023-11-30 16:27:11 25 4
gpt4 key购买 nike

谨慎起见,我首先要说我对 Rhino Mocks 和更普遍的模拟都是新手。

考虑到这一点,我正在尝试对我的 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”方法进行 stub 以提供可使用“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 理解的失败吗?

感谢您的帮助!

最佳答案

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

更新:

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

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

我只是将您的示例代码插入到单元测试中,并使用上述 stub 设置,测试通过。

关于c# - Rhino Mocks - 测试存储库层返回 "object reference not set to instance"错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8122145/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com