2013-02-07 17 views
0

我有一个资料库,如下面:犀牛嘲笑调用时获取参数的

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(); 
    } 
} 

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

[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()方法,试图从CreateCustomer()方法得到customerToUpdate实例。我如何编写断言来确保CreatedBy,CreateDate设置正确?

+1

''当你存根'Get'(是一个属性还是什么?我在上面显示的Repository 类中没有看到它)时会返回'nonLaborclassificationList',但它在此代码中的任何位置都没有定义。 –

回答

0

一般的策略是这样的:

  1. 存根库来返回你想要更新
  2. 采取必要行动的特定客户,即helper.CreateCustomer()
  3. 看看您最初存根对象有权设置的值

在这种情况下,您可能只需检查您创建的第一个被存入存储库的Customer对象。您正在测试的实际代码使用的是相同的对象(相同的参考),所以在InsertOnSubmit()获得对象时,您确实不需要最后一段代码。但是,如果你仍然想这样做,你可以使用AssertWasCalled的帮助:

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

要进行调试,也是一个GetArgumentsForCallsMadeOn方法是有用的,如果你可以使用调试器逐步完成。

0

有您的代码2个问题:

  1. 杰夫布里奇曼说,在评论,nonLaborclassificationList没有定义。我假设应该返回customerList

  2. InsertOnSubmit()对于repository在执行测试动作helper.CreateCustomer(1, customer.Id)后被勾住。所以这个存根不起作用。
    存根应设置在测试动作之前,因为排列

,当然,如果你想断言CreatedDate设置是否正确,您必须编写特定Assert为:)。