繁体   English   中英

单元测试时,我应该在ExpectedExceptionAttribute中使用哪种类型的异常?

[英]Which type of exception should I use in ExpectedExceptionAttribute while unit testing ?

我正在进行单元测试。 我想使用ExpectedExceptionAttribute。

我有一个员工类,其中包含我使用过索引的username属性,因此username应该是唯一的。

代码如下。

  public class EmployeeConfigration : EntityTypeConfiguration<Employee>
        {
            public EmployeeConfigration()
            {
                this.Property(x => x.FirstName).IsRequired().HasMaxLength(50);
                this.Property(t => t.UserName).HasColumnAnnotation(IndexAnnotation.AnnotationName, new IndexAnnotation(new IndexAttribute("IX_UserName", 1) { IsUnique = true }));

            }
        }

现在,考虑下面的单元测试代码。

 [TestMethod]
        [ExpectedException(typeof(System.Data.SqlClient.SqlException), "Username duplication is not allowded")]
        public void Insert_EmployeeWithSameUsername_Fails()
        {

          ...
          ...
          ...
          }

我已经使用了SqlException,但是它不起作用,它仍然会引发错误...在单元测试代码中应该使用哪种异常?

MSDN

如果抛出的异常继承自预期的异常,则测试将失败。

看来您实际上正在获得一个从SqlException派生的SqlException

使用它代替属性,或者最好使用xUnit / NUnit。

try
{
    //code
}
catch (SqlException se)
{

}
catch (Exception e)
{
    Assert.Fail(
         string.Format( "Unexpected exception of type {0} caught: {1}",
                        e.GetType(), e.Message )
    );
}

使用EF 6或更高版本时,违反唯一索引约束将引发DBUpdateException。 我不确定EF的早期版本。 唯一的问题是,只要数据库出现其他问题,就会引发DBUpdateException,因此没有明确的方法来测试唯一索引的冲突。 考虑以下代码:

        try
        {
           //some code here that causes the error
        }
        catch (DbUpdateException ex)
        {
            var updateException = ex.InnerException as UpdateException;

            if (updateException != null)
            {
                var sqlException = updateException.InnerException as SqlException;
                // UIX or PK violation, so try to update/insert.
                var uixViolationCode = 2601;
                var pkViolationCode = 2627;
                if (sqlException != null && sqlException.Errors.OfType<SqlError>().Any(se => se.Number == uixViolationCode || se.Number == pkViolationCode))
                {
                    // handle the required violation
                }
                else
                {
                    // it's something else...
                    throw;
                }
            }
            else
            {
                throw;
            }
        }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM