简体   繁体   中英

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

I am working on unit testing. I want to use ExpectedExceptionAttribute.

I have a employee class which contain the username property, on which I have used indexing, so username should be unique.

The code is as below.

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

            }
        }

Now, consider below code of unit testing.

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

          ...
          ...
          ...
          }

I have used SqlException, but its not working, it still throws an error... which kind of exception should I used in Unit testing code?

From MSDN :

The test will fail if the thrown exception inherits from the expected exception.

It looks like you're actually getting an exception that derives from SqlException .

Use this instead of the attribute, or better yet, use xUnit / NUnit if you can.

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

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

The violation of unique index constraint will throw DBUpdateException when using EF 6 or higher. I am not sure about eralier versions of EF. The only problem is that DBUpdateException is thrown whenever other problems occur with the data base, so there is no clear way in testing the violation of unique index. Consider this code:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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