A seemingly simple one here. How can I test the exception handling of this code block using a unit test?
public DbFactoryResponseType Close()
{
DbFactoryResponseType dbFactoryResponse = new DbFactoryResponseType();
try
{
if (m_isConnected)
{
m_isConnected = false;
if (m_hasRecordSet)
{
m_hasRecordSet = false;
m_dbFactoryDatabaseDataReader.Close();
m_dbFactoryDatabaseDataReader.Dispose();
}
m_dbFactoryDatabaseCommand.Dispose();
m_dbFactoryDatabaseConnection.Close();
m_dbFactoryDatabaseConnection.Dispose();
}
dbFactoryResponse.ExceptionMessage = "";
dbFactoryResponse.Success = true;
dbFactoryResponse.UserFriendlyMessage = "OK";
return dbFactoryResponse;
}
catch (Exception ex)
{
dbFactoryResponse.ExceptionMessage = ex.Message;
dbFactoryResponse.Success = false;
dbFactoryResponse.UserFriendlyMessage = "Error: Error while attempting to close the database connection.";
return dbFactoryResponse;
}
}
Here is what I have so far but I do not know how to make the exception fire allowing me to test the output.
/// <summary>
/// Test method to test closing a PosgreSQL database connection.
/// </summary>
[TestMethod]
public void TestClosePostgreSQLConnectionException()
{
const string connectionString = "Server=myIp;Port=myPort;Database=myDatabase;User Id=myUser;Password=myPassword;";
const string provider = "Npgsql";
DbProviderFactoryConnection aDbProviderFactoryConnection = new DbProviderFactoryConnection(connectionString, provider);
DbFactoryResponseType dbFactoryResponseType = aDbProviderFactoryConnection.Close();
Assert.IsNotNull(dbFactoryResponseType);
Assert.AreEqual(false, dbFactoryResponseType.Success);
}
You can create a mock version of
IDbFactoryDatabaseConnection(which is an interface that you will need to introduce), then in the setup of your mock, throw an exception when callingClose()on the mock and then in your test checkExceptionMessage,SuccessandUserFriendlyMessage.The way you do this is to use a mocking framework like Rhino Mocks or MoQ or you could even create a mock or stub of your own. You would then, in your test inject the mock version of the class into your class constructor (assuming you are using constructor injection rather than setter injection) and then you’ll be able to control the behaviour of your mock.
An example, using MoQ, of how you would do this is below:
Of course, in line with industry best practice this also means that you must adhere to SOLID principles, specifically the principle of Dependency Inversion, which means that you will need to create an interface for the DbFactoryDatabaseConnection class (I assume that is the name of your class), which is what I’ve shown in the example above.