我最近正在学习和使用 Polly 来为我的代码添加弹性,特别是对于超时和重试策略。但是,我不知道如何使用 polly 对代码进行单元测试。更具体地说,我不知道如何模拟以 Cancellation Token 作为参数的方法。下面是我的代码结构
public class Caller
{
private IHttpManager httpManager;
private IAsyncPolicy<HttpResponseMessage> policyWrap;
public Caller(IHttpManager httpManager, IAsyncPolicy<HttpResponseMessage> policyWrap)
{
this.httpManager= httpManager;
this.policyWrap = policyWrap;
}
public async Task CallThirdParty()
{
HttpResponseMessage httpResponse = await policyWrap.ExecuteAsync(async ct => await httpManager.TryCallThirdParty(ct), CancellationToken.None);
}
}
public interface IHttpManager
{
Task<HttpResponseMessage> TryCallThirdParty(CancellationToken cancellationToken);
}
Run Code Online (Sandbox Code Playgroud)
下面是我打算运行但不知道如何运行的单元测试。
[Test]
public void TestBehaviourUnderTimeoutPolicy()
{
// Set up the timeout policy such that the governed delegate will terminate after 1 sec if no response …Run Code Online (Sandbox Code Playgroud) 我有一个 JArray 类型的对象,其中包含 json 对象的列表。JArray 看起来像:
JArray jarray = [{"Key1":"v1"}, {"Key2":"v2"}, {"Key3":"v3"}]
Run Code Online (Sandbox Code Playgroud)
现在我想从 jarray 中检索一个元素,使得该元素包含给定的键名,例如,获取键名不是Key2or 的Key1元素Key3。在元素可能并不总是位于 jarray 中的同一位置以致我无法通过索引访问它的情况下,我该如何实现它?