簡體   English   中英

"如何對適配器類進行單元測試?"

[英]How do I unit test an adapter class?

假設我有來自第三方庫的以下類:

public class ThirdPartyType { ... }

public class ThirdPartyFunction
{
    public ThirdPartyType DoSomething() { ... }
}

實現細節並不重要,它們實際上不在我對這個第三方庫的控制范圍內。

假設我為ThirdPartyFunction編寫了一個適配器類:

public class Adapter
{
    private readonly ThirdPartyFunction f;

    public Adapter()
    {
        f = new ThirdPartyFunction();
    }

    public string DoSomething()
    {
        var result = f.DoSomething();

        // Convert to a type that my clients can understand
        return Convert(result);
    }

    private string Convert(ThirdPartyType value)
    {
        // Complex conversion from ThirdPartyType to string
        // (how do I test this private method?)
        ...
    }
}

如何測試我的Convert(ThirdPartyType)實現是否正確? 只有Adapter類才需要它,這就是它是私有方法的原因。

我建議將代碼提取到一個單獨的類,然后測試該類。 盡管它僅由該Adapter使用,但它不應該由Adapter負責進行轉換(與單一職責原則保持一致)。

通過提取它,您可以獨立於第三方代碼測試轉換器。

如果轉換器不需要任何狀態,您也可以將其設為靜態類,然后直接在您的適配器中引用它,而無需使用依賴注入注冊它。

如果您考慮一下,適配器不需要測試(因為它只是一個包裝器)但轉換器需要 - 因此將其提取到另一個類以允許對其進行測試是有意義的,即使它確實意味着另一個類代碼。

此外,將轉換器提取到單獨的類意味着如果ThirdPartyTypestring的格式發生更改,那么您可以在不影響Adapter實現的情況下進行更改。

如果您更改 Adapter 類以允許將 ThirdPartyFunction f 傳遞給它,那么您可以在測試類中使用它的模擬版本。 這將允許您測試轉換功能。

由於我不熟悉該語言,因此我不確定確切的語法,但我會嘗試一下:

public class Adapter
{
  private readonly ThirdPartyFunction f;

  // pass the function to the constructor when creating the adapter
  public Adapter(ThirdPartyFunction inputF)
    {
      f = inputF;
    }

  public string DoSomething()
  {
    var result = f.DoSomething();

    // Convert to a type that my clients can understand
    return Convert(result);
  }

  private string Convert(ThirdPartyType value)
  {
    // Complex conversion from ThirdPartyType to string
    // (how do I test this private method?)
    ...
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM