2012-05-16 124 views
2

這裏看似簡單的一個。我如何使用單元測試來測試這個代碼塊的異常處理?單元測試異常處理

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); 
    } 

回答

4

呼籲模擬,然後Close()在測試時,您可以創建IDbFactoryDatabaseConnection一個模擬的版本(這是,你將需要引入一個接口),然後在模擬的設置,拋出一個異常檢查ExceptionMessage,SuccessUserFriendlyMessage

你這樣做的方式是使用一個模擬框架,如Rhino Mocks或MoQ,或者你甚至可以創建一個你自己的模擬或存根。然後,在你的測試中,將類的模擬版本注入你的類構造函數(假設你使用構造函數注入而不是setter注入),然後你將能夠控制你的模擬行爲。

一個例子,使用最小起訂量,你會怎麼做,這是下面:

Mock<IDbFactoryDatabaseConnection> connectionMock = new Mock<IDbFactoryDatabaseConnection>(); 

DbProviderFactoryConnection aDbProviderFactoryConnection = new DbProviderFactoryConnection(connectionString, provider, connectionMock.Object); 

connectionMock.Setup(c => c.Close()).Throws<Exception>(); 

DbFactoryResponseType dbFactoryResponseType = aDbProviderFactoryConnection.Close(); 

當然,在同行業最佳做法,這也意味着你必須堅持SOLID原則,具體原則依賴倒置,這意味着您將需要爲DbFactoryDatabaseConnection類創建一個接口(我假設這是您的類的名稱),這正如我在上面的示例中所示。

+0

你有任何鏈接或例子,我將如何做到這一點? – CSharpened

+1

哦,是的,我將很快發佈一個 –

+0

優秀。謝謝 – CSharpened