Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/302.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
c#测试一般异常_C#_Unit Testing_Exception_Xunit - Fatal编程技术网

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