سؤال

I start learn Moq and I have this problem. I need mock class/interface which make HTTP GET and HTTP POST request and return HTML string as server response.

I simplified my code. Here is:

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

I use IHttpManager in class ConnectionManager which make log in or log off on server.

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
    }

    // ...
}

I unit test for method LogIn. I would like to mock IHttpManager. But I don’t how to do in correct way.

I try this:

// 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
هل كانت مفيدة؟

المحلول

Seems like you need to set up the parameter expectations on your mock:

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

Ideally, you should use It.Is<T>() to match the arguments, to ensure that the method is called with the exact parameters you expect. For example, you may want to test that your Login method calls HttpGet with ServerUrl.LogOn:

It.Is<Uri>(uri => uri == ServerUrl.LogOn),
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top