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

现在 System under Test 类如下所示:

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()方法的地方,试图customerToUpdate从方法中获取实例CreateCustomer()。如何编写断言以确保CreatedBy正确CreateDate设置?

4

2 回答 2

0

您的代码中有两个问题:

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

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

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

于 2013-03-02T10:20:34.853 回答
0

一般的策略是这样的:

  1. 存根存储库以返回您要更新的特定客户
  2. 采取必要的行动,即helper.CreateCustomer()
  3. 查看您最初存根的对象是否设置了正确的值

在这种情况下,您可能只需检查您创建的第一个 Customer 对象,该对象被存根到存储库中。您正在测试的实际代码使用相同的对象(相同的引用),因此您真的不需要从中获取对象的最后一段代码InsertOnSubmit()。但是,如果您仍然想这样做,您可以使用AssertWasCalled以下方式提供帮助:

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

对于调试,如果您可以使用调试器单步执行,还有一种GetArgumentsForCallsMadeOn方法很有用。

于 2013-02-21T23:05:42.863 回答