1

我开始学习起订量,但我遇到了这个问题。我需要模拟类/接口来发出 HTTP GET 和 HTTP POST 请求并返回 HTML 字符串作为服务器响应。

我简化了我的代码。这是:

public interface IHttpManager
{
    /// <summary>
    /// Make HTTP GET request on server and return HTML string
    /// </summary>
    string HttpGet(Uri url, CookieContainer cookies, HttpRequestSettings settings);

    /// <summary>
    /// Make HTTP POST request and return HTML string
    /// </summary>
    string HttpPost(Uri url, string postData, CookieContainer cookies, HttpRequestSettings settings);
}

IHttpManager在课堂ConnectionManager上使用登录或注销服务器。

public interface IConectionManager
{
    /// <summary>
    /// Connect to server and parse HTML response
    /// </summary>
    Result<T> LogIn(string nick, string password);

    /// <summary>
    /// Log off and parse HTML response
    /// </summary>
    /// <param name="account"></param>
    void LogOff(Acccount account);
}

public class ConnectionManager : IConectionManager
{
    private IHttpManager _httpManager;
    private HttpRequestSettings _httpRequestSettings;

    public ConnectionManager(IHttpManager httpManager, HttpRequestSettings httpRequestSettings)
    {
        _httpManager = httpManager;
        _httpRequestSettings = httpRequestSettings;
    }

    public Result<Account> LogIn(string nick, string password)
    {
        // I simplified this method

        // How correct mock IHttpManager, because it must return HTML string
        // so in Moq in Setup return hard coded HTML string which represent server response ?
        string htmlStringResponse = _httpManager.HttpGet(ServerUrl.LogOn, new CookieContainer(), _httpRequestSettings);

        // parse HTML string and return result
    }

    // ...
}

我对方法进行单元测试LogIn。我想嘲笑IHttpManager. 但我不知道如何以正确的方式去做。

我试试这个:

// Arrange
var mockHttpManager = new Mock<IHttpManager>();

mockHttpManager.Setup(x=>x.HttpGet()).Returns(()=>"HTML SERVER RESPONSE");

var sut = new ConnectionManager(mockHttpManager.Object, new HttpRequestSettings());

// act
sut.Login("nick", "123")

// Assert
4

1 回答 1

3

似乎您需要在模拟中设置参数期望:

mockHttpManager
    .Setup(x => x.HttpGet(
        It.IsAny<Uri>(),
        It.IsAny<CookieContainer>(),
        It.IsAny<HttpRequestSettings>()))
    .Returns(() => "HTML SERVER RESPONSE");

理想情况下,您应该使用It.Is<T>()来匹配参数,以确保使用您期望的确切参数调用该方法。例如,您可能想测试您的方法是否Login调用:HttpGetServerUrl.LogOn

It.Is<Uri>(uri => uri == ServerUrl.LogOn),
于 2013-10-24T16:26:05.220 回答