Reputation: 1541
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?
Upvotes: 0
Views: 260
Reputation: 68740
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 )
);
}
Upvotes: 1
Reputation: 61
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;
}
}
Upvotes: 0