-
-
Notifications
You must be signed in to change notification settings - Fork 374
/
Copy pathMockAPIRequestMaker.cs
71 lines (67 loc) · 2 KB
/
MockAPIRequestMaker.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using ExchangeSharp;
namespace ExchangeSharpTests
{
public class MockAPIRequestMaker : IAPIRequestMaker
{
/// <summary>
/// Use a global response for all requests
/// </summary>
public string GlobalResponse { get; set; }
/// <summary>
/// Otherwise lookup the url in the dictionary and find the response, which is string result or Exception to throw
/// </summary>
public Dictionary<string, object> UrlAndResponse = new Dictionary<string, object>();
/// <summary>
/// Request state changed
/// </summary>
public Action<IAPIRequestMaker, RequestMakerState, object> RequestStateChanged { get; set; }
/// <summary>
/// Make a mock request
/// </summary>
/// <param name="url"></param>
/// <param name="baseUrl"></param>
/// <param name="payload"></param>
/// <param name="method"></param>
/// <returns></returns>
public async Task<IAPIRequestMaker.RequestResult<string>> MakeRequestAsync(
string url,
string baseUrl = null,
Dictionary<string, object> payload = null,
string method = null
)
{
await new SynchronizationContextRemover();
RequestStateChanged?.Invoke(this, RequestMakerState.Begin, null);
if (GlobalResponse != null)
{
RequestStateChanged?.Invoke(this, RequestMakerState.Finished, GlobalResponse);
return new IAPIRequestMaker.RequestResult<string>() { Response = GlobalResponse };
}
else if (UrlAndResponse.TryGetValue(url, out object response))
{
if (!(response is Exception ex))
{
RequestStateChanged?.Invoke(
this,
RequestMakerState.Finished,
response as string
);
return new IAPIRequestMaker.RequestResult<string>()
{
Response = response as string
};
}
RequestStateChanged?.Invoke(this, RequestMakerState.Error, ex);
throw ex;
}
return new IAPIRequestMaker.RequestResult<string>()
{
Response = @"{ ""error"": ""No result from server"" }"
};
}
}
}