我开始学习起订量,但我遇到了这个问题。我需要模拟类/接口来发出 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