簡體   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