如何使用LINQ表达式从模拟的存储库返回新对象?

时间:2015-05-29 17:47:01

标签: c# linq rhino-mocks

我正在使用Rhino Mocks并创建了一个模拟存储库。

var salesForcePolicies = MockRepository.GenerateMock<IRepository<SalesForcePolicy>>();

我有一个私有方法从存储库中返回policy项。

private SalesForcePolicy GetSalesForcePolicyByClientId(decimal clientId)
{
    var policy = salesForcePolicies.FindByExp(x => x.IdNumber == clientId).FirstOrDefault();
    if (policy == null) throw new AccountUpdaterException("Policy Not Found in Sales Force Lookup Table.");
    return policy;
}

我试图让存储库在private方法中调用查询时返回一个具有一个属性集的新对象。我不想打破封装并设置为public virtual

编写时,编译器正在尖叫......

var clientId = decimal.Parse("123456");
salesForcePolicies.Stub(x => x.FindByExp(y => y.IdNumber == clientId)).Return(new SalesForcePolicy { PolicyNumber = "123456" });

如何让这个模拟的存储库在查询时返回一个新对象?

Error: The best overloaded method match for 'Rhino.Mocks.Interfaces.IMethodOptions<System.Linq.IQueryable<Data.Models.Ussi.SalesForcePolicy>>.Return(System.Linq.IQueryable<Data.Models.Ussi.SalesForcePolicy>)' has some invalid arguments.

1 个答案:

答案 0 :(得分:0)

这方面的技巧是传递null表达式参数,然后使用.IgnoreArguments()。对于返回,请创建new List<T>()并致电.AsQueryable()

[TestMethod]
public void Can_Mock_Sales_Force_Repo()
{
    // arrange
    var salesForcePolicyRepo = MockRepository.GenerateMock<IRepository<SalesForcePolicy>>();

    // act
    var clientId = decimal.Parse("123456");
    var salesForcePolicy = new SalesForcePolicy { PolicyNumber = "123456" };
    IEnumerable<SalesForcePolicy> salesForcePolicies = new List<SalesForcePolicy> { salesForcePolicy };
    salesForcePolicyRepo.Stub(x => x.FindByExp(null)).IgnoreArguments().Return(salesForcePolicies.AsQueryable());
    var policy = salesForcePolicyRepo.FindByExp(x => x.IdNumber == clientId).FirstOrDefault();

    // assert
    Assert.IsTrue(policy == salesForcePolicy);
}