我正在尝试为 DelegatingHandler 编写一个集成测试,以防止重复请求。处理程序检查数据库以查看请求是否已被处理,如果在前一个请求仍在运行时发出重复请求,则返回 407-Conflict。
我的测试中有以下代码:
HttpClient client = new HttpClient();
var responseTask1 = client.PostAsJsonAsync(RequestUriWithDuplicatePrevention, ReadRequestContent("DuplicateRequestJsonContent.json"));
var responseTask2 = client.PostAsJsonAsync(RequestUriWithDuplicatePrevention, ReadRequestContent("DuplicateRequestJsonContent.json"));
var response1 = responseTask1.Result;
var response2 = responseTask2.Result;
两个请求同时记录到数据库中。如何将第二个请求延迟一段时间?
我试过添加一个 Thread.Sleep(500) 但它似乎没有什么不同。
修订代码
这段代码似乎大部分时间都可以工作,但它不是 100% 可靠的。
[TestMethod]
public void ShouldReturn407ConflictWhenDuplicateRequestSubmitted()
{
var results = ExecutePostRequests().Result;
Assert.AreEqual(HttpStatusCode.OK, results[0].StatusCode);
Assert.AreEqual(HttpStatusCode.Conflict, results[1].StatusCode);
}
private async Task<HttpResponseMessage[]> ExecutePostRequests()
{
HttpClient client = new HttpClient();
var task1 = ExecutePost(client, 0);
var task2 = ExecutePost(client, 4000);
var response1 = await task1;
var response2 = await task2;
return new[] {response1, response2};
}
private async Task<HttpResponseMessage> ExecutePost(HttpClient client, int delay)
{
await Task.Delay(delay);
return await client.PostAsync(RequestUriWithDuplicatePrevention,
ReadRequestContent("DuplicateRequestJsonContent.json"));
}
正在执行的 Web 服务有一个 Thread.Sleep(5000)。