在单元测试中模拟HttpClient

我在尝试包装要在单元测试中使用的代码时遇到了一些问题。问题是这样的。我有接口IHttpHandler:


public interface IHttpHandler

{

    HttpClient client { get; }

}

和使用它的类,HttpHandler:


public class HttpHandler : IHttpHandler

{

    public HttpClient client

    {

        get

        {

            return new HttpClient();

        }

    }

}

然后是Connection类,该类使用simpleIOC注入客户端实现:


public class Connection

{

    private IHttpHandler _httpClient;


    public Connection(IHttpHandler httpClient)

    {

        _httpClient = httpClient;

    }

}

然后我有一个具有此类的单元测试项目:


private IHttpHandler _httpClient;


[TestMethod]

public void TestMockConnection()

{

    var client = new Connection(_httpClient);


    client.doSomething();  


    // Here I want to somehow create a mock instance of the http client

    // Instead of the real one. How Should I approach this?     


}

现在显然我将在Connection类中具有从后端检索数据(JSON)的方法。但是,我想为此类编写单元测试,显然我不想针对真正的后端编写测试,而只是想模拟一个后端。我曾试图用谷歌搜索一个很好的答案,但没有成功。我可以并且曾经使用过Moq进行模拟,但是从未使用过诸如httpClient之类的东西。我应该如何解决这个问题?


提前致谢。


白衣染霜花
浏览 1019回答 3
3回答
打开App,查看更多内容
随时随地看视频慕课网APP