测试用例:当我编辑客户时,由于某种原因存储库无法更新,服务应返回此异常。
测试方法:
public bool EditCustomer(CustomerViewModel customerToEdit)
{
return _repository.Update(customerToEdit.ToEntity());
}
[TestFixtureSetUp]
public void SetUp()
{
this._customerRepositoryMock = Substitute.For<ICustomerRepository>();
this._customerService = new CustomerService(this._customerRepositoryMock);
}
[Test]
public void EditCustomerShouldReturnTrueWhenCustomerIsCreated()
{
var c = new CustomerViewModel();
_customerRepositoryMock.Update(c.ToEntity()).Returns(x => {throw new Exception();});
Assert.Throws<Exception>(() => _customerService.EditCustomer(c));
}
此测试用例将不起作用,因为customerToEdit.ToEntity()!= c.ToEntity()因为它们不引用同一个对象。有没有办法测试这个案例?或者我应该重写整个应用程序,并让控制器负责从实体转换到实体?
答案 0 :(得分:1)
我不确定您使用的是哪个库,但使用Moq可以通过多种方式实现:
var viewModel = new CustomerViewModel();
var customerRepositoryMock = new Mock<ICustomerRepository>();
// If you just want to test out the behavior of an exception being thrown,
// regardless of what is passed in
customerRepositoryMock
.Setup(r => r.Update(It.IsAny<CustomerViewModel>()))
.Throws<Exception>();
// If you need to throw an exception when the viewmodel contains certain properties
customerRepositoryMock
.Setup(r => r.Update(It.Is<CustomerViewModel>(c => c.Id == viewModel.Id)))
.Throws<Exception>();
// If you need to throw an exception with specific properties, and verify those
customerRepositoryMock
.Setup(r => r.Update(It.Is<CustomerViewModel>(c => c.Id == viewModel.Id)))
.Throws(new Exception("some message"));
然后,您可以按照已经定义的那样执行断言。
我在这里省略了你的ToEntity()
方法,因为重点是向你展示更多“宽松”的方法来确定输入参数的相等性,例如按类型或属性,而不仅仅是通过引用。