【发布时间】: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