c#测试一般异常
我正在为一个在c#测试一般异常,c#,unit-testing,exception,xunit,C#,Unit Testing,Exception,Xunit,我正在为一个在MySQL数据库上运行的存储库类编写集成测试 我想测试一个事实,即插入同一条记录两次会引发异常,我使用的是xUnit [Fact] public void Insert_SamePaymentTwoTimes_ThrowInvalidOperationException() { Payment payment; using (var transaction = new TransactionScope()) {
MySQL
数据库上运行的存储库类编写集成测试
我想测试一个事实,即插入同一条记录两次会引发异常,我使用的是xUnit
[Fact]
public void Insert_SamePaymentTwoTimes_ThrowInvalidOperationException()
{
Payment payment;
using (var transaction = new TransactionScope())
{
int? id = 0;
id = paymentRepository.Insert(testPayment);
payment = paymentRepository.GetById(id);
Assert.Throws<MySql.Data.MySqlClient.MySqlException>(() => paymentRepository.Insert(payment));
}
}
并在我的测试中捕获该异常:
[Fact]
public void Insert_SamePaymentTwoTimes_ThrowInvalidOperationException()
{
Payment payment;
using (var transaction = new TransactionScope())
{
int? id = 0;
id = paymentRepository.Insert(testPayment);
payment = paymentRepository.GetById(id);
Assert.Throws<InvalidOperationException>(() => paymentRepository.Insert(payment));
}
}
[事实]
public void Insert_samepaymenttwo_ThrowInvalidOperationException()
{
支付;
使用(var transaction=new TransactionScope())
{
int?id=0;
id=paymentRepository.Insert(testPayment);
payment=paymentRepository.GetById(id);
Assert.Throws(()=>paymentRepository.Insert(payment));
}
}
有没有其他方法可以替代这种方法?我在考虑可能实现一个定制的
DbException
,以便尽可能通用。DbException
比无效操作异常
更有意义。除非您试图隐藏异常源,否则请记住使用源异常对象初始化新异常-否则会破坏堆栈跟踪。您不需要自定义DbException
,因为这样做。知道这一点很好,但如何使其工作?1。在测试中,将InvalidOperationException
替换为DbException
。2.3.利润!你也不需要捕捉或重新捕获任何东西;所有ADO.NET数据库异常都源自DbException
,无论您使用的是哪种提供程序。它不起作用,我的测试失败,原因是:Assert.Throws()失败预期:typeof(System.Data.Common.DbException)实际:typeof(MySql.Data.MySqlClient.MySqlException):
[Fact]
public void Insert_SamePaymentTwoTimes_ThrowInvalidOperationException()
{
Payment payment;
using (var transaction = new TransactionScope())
{
int? id = 0;
id = paymentRepository.Insert(testPayment);
payment = paymentRepository.GetById(id);
Assert.Throws<InvalidOperationException>(() => paymentRepository.Insert(payment));
}
}