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.
I prefer GarethOwen’s answer (the ExpectedException attribute) or this way:
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.