当被称为争论时,犀牛嘲笑

时间:2013-02-07 17:05:56

标签: c# mocking rhino-mocks

我有一个如下所示的存储库:

internal class Repository<T> : IRepository<T> where T : class
{
    public virtual ITable GetTable()
    {
        return _context.GetTable<T>();
    }

    public virtual void InsertOnSubmit(T entity)
    {
        GetTable().InsertOnSubmit(entity);
    }

    public virtual void SubmitChanges()
    {
        _context.SubmitChanges();
    }
}

现在,受测试的系统类如下所示:

public class CustomerHelper
{
    private readonly IRepository<Customer> _customerRepository;
    CustomerHelper(IRepository<Customer> customerRepository)
    {
        _customerRepository = customerRepository;
    }

    public void CreateCustomer(int createdBy, int customerId)
    {
        var customerToUpdate = _customerRepository.Get.Single(c => c.Id == customerId)

        customerToUpdate.CreatedBy =createdBy;
        customerToUpdate.CreateDate = DateTime.Now;

        _customerRepository.InsertOnSubmit(customerToUpdate);
        _customerRepository.SubmitChanges();
    }
}

我使用RhinoMocks对CreateCustomer方法的测试方法,如下所示。

[TestMethod]
public void CreateCustomer()
{
    // Arrange
    Customer customer = new Customer
    {
        Id = 1
    };
    IRepository<Customer> repository =  MockRepository.GenerateMock<IRepository<Customer>>();
    var customerList = new List<Customer> { customer }.AsQueryable();

    repository.Stub(n => n.Get).Return(nonLaborclassificationList);

    CustomerHelper helper = new Customer(repository);
    helper.CreateCustomer(1, customer.Id);

    // Now here I would liek to test whether CreatedBy, CreateDate fields on    cutomer are updated correctly. I've tried the below

    Customer customerToUpdate;

    repository.Stub(c => c.InsertOnSubmit(customer)).WhenCalled(c => { customerToUpdate = n.Arguments[0]; } );
    Assert.AreEqual(1, customerToUpdate.CreatedBy);
}

以上代码无效。我正在使用InsertOnSubmit()方法进行存根的地方,尝试从customerToUpdate方法获取CreateCustomer()实例。如何编写断言以确保CreatedByCreateDate设置正确?

2 个答案:

答案 0 :(得分:0)

总体战略是:

  1. 存储存储库以返回您要更新的特定客户
  2. 采取必要的行动,即helper.CreateCustomer()
  3. 查看您最初存根的对象是否设置了正确的值
  4. 在这种情况下,您可能只需检查您创建的第一个Customer对象,该对象存入存储库。您正在测试的实际代码使用相同的对象(相同的引用),因此您实际上不需要从InsertOnSubmit()获取对象的最后一段代码。但是,如果您仍想这样做,可以使用AssertWasCalled来提供帮助:

    repository.AssertWasCalled(
      x => x.InsertOnSubmit(Arg<Customer>.Matches(c => c.CreateBy))
    

    对于调试,还有一个GetArgumentsForCallsMadeOn方法,如果您可以逐步使用调试器,这个方法很有用。

答案 1 :(得分:0)

您的代码中有2个问题:

  1. 正如Jeff Bridgman在评论中所说,nonLaborclassificationList未定义。我认为应该返回customerList

  2. 执行测试操作InsertOnSubmit()后,repository
  3. helper.CreateCustomer(1, customer.Id)被存根。所以这个存根不起作用 应该在测试操作之前设置存根,因为安排 Act 之前进行。

  4. 当然,如果你想断言CreatedDate是否设置正确,你必须为此编写特定的Assert