Reputation: 585
I have a Repositry class wich initiates like this:
public ContactRepository(string sqlStr, string username)
{
if (!string.IsNullOrEmpty(sqlStr))
{
ent = new AceoEntities(sqlStr);
Username = username;
}
else
new Exception("No sql string is defined");
}
This might not be the best method, but I would like to make sure it's not possible to create an instance off the class without sqlStr.
Then I'm trying to test this:
[TestMethod()]
public void CreateContactRepositoryWithEmtySqlString()
{
string sqlStr = string.Empty;
ContactRepository target;
try
{
target = new ContactRepository("kvelland-kk", sqlStr);
}
catch (Exception e)
{
Assert.AreEqual("No sql string is defined",e.Message);
}
}
My question is: Is this the correct way to to this? I' having problems getting this to work.
Upvotes: 1
Views: 716
Reputation: 6133
I would rather use the ExpectedException attribute to mark your TestMethod, and throw a more specific type of exception, for example an ArgumentException:
[TestMethod()]
[ExpectedException(typeof(System.ArgumentException))]
public void CreateContactRepositoryWithEmtySqlString()
{
ContactRepository target = new ContactRepository("kvelland-kk", string.Empty);
}
Upvotes: 3
Reputation: 9173
I prefer GarethOwen's answer (the ExpectedException attribute) or this way:
public void MyTest()
{
try
{
target = new ContactRepository("kvelland-kk", sqlStr);
Assert.Fail("Should have failed with MyExceptionType");
}
catch(MyExceptionType){}
}
Checking exception messages is not a good idea. Cause you may get a different message based on the system localisation. Check for the exception type instead. And as Xhalent mentioned don't throw the a Exception, throw a specific type of exception.
Upvotes: 0
Reputation: 3954
you forgot the throw the new Exception
throw new Exception("No sql string is defined");
Interestingly, this kind of demonstrates the value of unit tests, as they have shown up a simple coding error easily over looked.
Upvotes: 0