这里看似简单的一个。如何使用单元测试测试此代码块的异常处理?
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;
}
}
这是我到目前为止所拥有的,但我不知道如何让异常触发以允许我测试输出。
/// <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);
}