[英]Mock a class in another class in C# unit test
例如,
我在其他地方定義了一個 class:
using ...;
namespace abc.Client
{
public class ByoIpClient : ServiceClient<ByoIpClient>
{
public static ByoIpClient CreateByoIpClient(SomeSettings someSettings);
}
}
它被用在我的項目中
using abc.Client; //using the class defined above
public class BYOIPManager
{
private ByoIpClient byoIpClient;
public void Start()
{
this.byoIpClient = ByoIpClient.CreateByoIpClient(someSettings);
}
}
現在我想為class BYOIPManager寫一個測試,但是我不想使用定義的byoIpClient。 但是我想寫另一個 mockByoipClient 來替換 ByoipClient class。我該怎么做? 謝謝!
[TestClass]
public class BYOIPOrchestrationEngineTests
{
private BYOIPManager byoipManager;
[TestInitialize]
public void TestInitialize()
{
this.byoipManager = new BYOIPManager();
// I need this byoIpManager to use my mockByoIpClient rather than the real byoIpClient
}
}
這就是我在評論中的意思。 說你的 static class,你不能編輯,這是(愚蠢):
public static class ByoIpClient
{
public static string DoWork(string settings)
{
return "real work"
}
}
創建具有相同方法簽名的接口:
public interface IByoIpClient
{
string DoWork(string settings);
}
然后創建一個實現您的接口的 class,並直接傳遞給 static class:
public class InjectableByoIpClient : IByoIpClient
{
public string DoWork(string settings) => ByoIpClient.DoWork(settings);
}
現在可以用DI設置這個class,在BYOIPManager
的構造函數中接受接口
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.