我有一个如下所示的存储库:
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()
实例。如何编写断言以确保CreatedBy
,CreateDate
设置正确?
答案 0 :(得分:0)
总体战略是:
helper.CreateCustomer()
在这种情况下,您可能只需检查您创建的第一个Customer对象,该对象存入存储库。您正在测试的实际代码使用相同的对象(相同的引用),因此您实际上不需要从InsertOnSubmit()
获取对象的最后一段代码。但是,如果您仍想这样做,可以使用AssertWasCalled
来提供帮助:
repository.AssertWasCalled(
x => x.InsertOnSubmit(Arg<Customer>.Matches(c => c.CreateBy))
对于调试,还有一个GetArgumentsForCallsMadeOn
方法,如果您可以逐步使用调试器,这个方法很有用。
答案 1 :(得分:0)
您的代码中有2个问题:
正如Jeff Bridgman在评论中所说,nonLaborclassificationList
未定义。我认为应该返回customerList
。
InsertOnSubmit()
后,repository
的 helper.CreateCustomer(1, customer.Id)
被存根。所以这个存根不起作用
应该在测试操作之前设置存根,因为安排在 Act 之前进行。
当然,如果你想断言CreatedDate
是否设置正确,你必须为此编写特定的Assert
。