对象未设置为rhino mocks中对象的实例

时间:2014-02-11 16:09:04

标签: c# asp.net unit-testing mocking nunit

更新:3

我试图模拟一个类用于通过工作单元创建其他类的新实例的方法。当我尝试模拟返回固定数据的方法时,在调用getPage方法时,我得到一个null而不是列表。

这是我的代码

[TestFixture()]
public class CustomerServiceTests
{
    private ICustomerService service;
    private IUnitOfWork mockUnitOfWork;
    private IGenericRepository<Entities.Customer> repository;

    private int customerId;
    private int ContactId;

    [SetUp()]
    public void Setup()
    {
        customerId = 1;
        ContactId = 1;
    }

  [Test()]
    public void GetCustomers_should_return_three_results()
    {
        mockUnitOfWork = MockRepository.GenerateMock<IUnitOfWork>();
        repository = MockRepository.GenerateMock<IGenericRepository<Entities.Customer>>();

        List<Entities.Customer> customerList = new List<Entities.Customer>
        {
            new Entities.Customer { Id = 1, CompanyName = "test1", ContractorId = 1 },
            new Entities.Customer { Id = 2, CompanyName = "test2", ContractorId = 2 },
            new Entities.Customer { Id = 3, CompanyName = "test3", ContractorId = 1 },
            new Entities.Customer { Id = 4, CompanyName = "test4", ContractorId = 1 },
            new Entities.Customer { Id = 5, CompanyName = "test5", ContractorId = 4 }
        };


        var IQueryableList = customerList.AsEnumerable();            
        mockUnitOfWork.Stub(uow => uow.CustomerRepository).Return(repository);




        repository.Stub(repo => repo.GetPaged()).Return(new ContentList<Entities.Customer> { List = IQueryableList, Total = customerList.Count });

        service = new CustomerService(mockUnitOfWork);

        var resultList = service.GetCustomers(new PageRequest {PageSize = 20, PageIndex = 1 });
        var total = resultList.Data.Total;
        Assert.AreEqual(10, total);
    }

服务代码的一部分返回null而不是提供的列表。

            customers = _service.CustomerRepository.GetPaged(filter, orderBy, pageRequest.PageSize, pageRequest.PageIndex, "CustomersContacts");

1 个答案:

答案 0 :(得分:5)

为没有参数的GetPaged设置存根

GetPaged()

但是你用参数

调用GetPaged
GetPaged(filter, orderBy, pageRequest.PageSize, pageRequest.PageIndex, "CustomersContacts")

尝试这样的事情(你需要验证语法,确保它是正确的类型)

repository
    .Stub(repo => repo.GetPaged(
        Arg<string>.Is.Anything, 
        Arg<string>.Is.Anything,  
        Arg<int>.Is.Anything, 
        Arg<int>.Is.Anything, 
        Arg<string>.Is.Anything))
    .Return(new ContentList<Entities.Customer> { List = IQueryableList, Total = customerList.Count });