如何使用该POST方法发出HTTP请求并发送一些数据?我可以做GET请求,但不知道如何制作POST.
我正在阅读Dino Esposito关于如何在ASP.NET MVC中测试AsyncConrollers的文章,在那里他使用了"Humble Object"模式,而没有详细介绍.
谷歌周围也没有运气.
那么,Humble Object模式是什么?什么时候有用?
我想单元测试我执行的方法和异步操作:
Task.Factory.StartNew(() =>
{
// method to test and return value
var result = LongRunningOperation();
});
Run Code Online (Sandbox Code Playgroud)
我在单元测试中编写必要的方法等(用c#编写),但问题是在断言测试之前异步操作没有完成.
我怎么能绕过这个?我应该创建TaskFactory的模拟或任何其他单元测试异步操作的技巧吗?
我正在使用 xUnit 和 Moq 编写测试用例。
我正在尝试模拟 HttpClient 的 PostAsync(),但出现错误。
下面是用于模拟的代码:
public TestADLS_Operations()
{
var mockClient = new Mock<HttpClient>();
mockClient.Setup(repo => repo.PostAsync(It.IsAny<string>(), It.IsAny<HttpContent>())).Returns(() => Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK)));
this._iADLS_Operations = new ADLS_Operations(mockClient.Object);
}
Run Code Online (Sandbox Code Playgroud)
错误:
不支持的表达式:repo => repo.PostAsync(It.IsAny(), It.IsAny()) 不可覆盖的成员(此处:HttpClient.PostAsync)不能在设置/验证表达式中使用。
截屏:
.NET Core 2.1带有一个称为的新工厂HttpClientFactory,但是我不知道如何模拟它来对包含REST服务调用的某些方法进行单元测试。
正在使用.NET Core IoC容器注入工厂,该方法的作用是从工厂创建一个新客户端:
var client = _httpClientFactory.CreateClient();
Run Code Online (Sandbox Code Playgroud)
然后使用客户端从REST服务获取数据:
var result = await client.GetStringAsync(url);
Run Code Online (Sandbox Code Playgroud) 我正在尝试使用NSubstitute来模拟 HttpClient。这是代码:
public static HttpClient GetHttpClient(bool isSucess = true, string methodType = "GET")
{
var mockIHttpMessageHandler = Substitute.For<IMockHttpMessageHandler>();
var mockHttpMessageHandler = Substitute.For<MockHttpMessageHandler>(mockIHttpMessageHandler);
var httpResponse = Substitute.For<HttpResponseMessage>();
httpResponse.Content = new StringContent("\"test\"");
if (isSucess)
httpResponse.StatusCode = HttpStatusCode.OK;
else
httpResponse.StatusCode = HttpStatusCode.NotFound;
var mockHttpClient = Substitute.For<HttpClient>(mockHttpMessageHandler);
mockHttpClient.BaseAddress = new Uri("http://localhost");
if(methodType != "POST"){
mockHttpClient.GetAsync(Arg.Any<Uri>()).ReturnsForAnyArgs(httpResponse);
}
return mockHttpClient;
}
Run Code Online (Sandbox Code Playgroud)
但是,我在这一行遇到错误:
mockHttpClient.GetAsync(Arg.Any<Uri>()).ReturnsForAnyArgs(httpResponse);
Run Code Online (Sandbox Code Playgroud)
错误是
NSubstitute.Exceptions.RedundantArgumentMatcherException:'上次调用后留下了一些参数规范(例如 Arg.Is、Arg.Any)。
这通常是由于使用参数规范来调用 NSubstitute 无法处理的成员(例如非虚拟成员或对非替代实例的调用),或者出于指定调用以外的目的(例如使用 arg 规范作为返回值)。例如:
Run Code Online (Sandbox Code Playgroud)var sub = Substitute.For<SomeClass>(); var realType = new MyRealType(sub); // INCORRECT, arg spec …
我将在 Xamarin 中创建一个新应用程序,并且由于客户的需求,我需要对几乎所有内容创建单元测试。
在我的应用程序中,我使用 HttpClient,并且必须设置超时,因为应用程序必须上传图像。
但我怎样才能进行单元测试呢HttpClient.Timeout?
其他所有内容都是使用 模拟的HttpMessageHandler,但在其中插入Task.Delay不会影响它。
编辑
添加代码以进行澄清
public async Task ExecuteAsync_NotExecutedWithinTimeout_ThrowsExecption()
{
// Arrange
var endpoint = "http://google.dk/";
var method = HttpMethod.Get;
var timeoutClient = TimeSpan.FromMilliseconds(2);
var timeoutServer = TimeSpan.FromMilliseconds(10);
var requestor = new Requestor(new MessageHandler { Method = HttpMethod.Get, Timeout = timeoutServer, URL = url });
bool result = false;
// Act
try
{
await requestor.ExecuteAsync(method, endpoint, timeout: timeoutClient);
}
catch (TimeoutException)
{
result = true;
}
// Assert
Assert.AreEqual(true, …Run Code Online (Sandbox Code Playgroud) 我有一个使用 执行请求的服务方法HttpClient。服务类构造函数IHttpClientFactory使用以下代码注入并创建客户端:
_httpClient = httpClientFactory.CreateClient(url);
Run Code Online (Sandbox Code Playgroud)
在我的测试构造函数中,我试图模拟PostAsync方法响应。
public MyServiceUnitTests()
{
_HttpClientMock = new Mock<IHttpClientFactory>();
var mockHttpMessageHandler = new Mock<HttpMessageHandler>();
mockHttpMessageHandler.Protected()
.Setup<Task<HttpResponseMessage>>("PostAsync", ItExpr.IsAny<string>(), ItExpr.IsAny<HttpContent>())
.ReturnsAsync(new HttpResponseMessage{ StatusCode = HttpStatusCode.OK });
var httpClient = new HttpClient(mockHttpMessageHandler.Object);
_HttpClientMock.Setup(x => x.CreateClient(It.IsAny<string>())).Returns(httpClient);
_Service = new MyService(_HttpClientMock.Object);
}
Run Code Online (Sandbox Code Playgroud)
设置mockHttpMessageHandler 时出现以下错误:System.ArgumentException: 'No protected method HttpMessageHandler.PostAsync found whose signature is compatible with the provided arguments (string, HttpContent).'
我究竟做错了什么?
c# ×8
unit-testing ×5
.net ×3
moq ×3
httpclient ×2
asp.net-core ×1
asynchronous ×1
httprequest ×1
nsubstitute ×1
post ×1
testing ×1
virtual ×1
xamarin ×1
xunit ×1