-
Notifications
You must be signed in to change notification settings - Fork 0
/
CoinCapData.cs
162 lines (135 loc) · 5.63 KB
/
CoinCapData.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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
public async Task<CoinCapData> GetCurrencyData( string id )
{
return
(await memoryCache.GetOrCreateAsync(
$"{this.GetType().Name}.{id}",
async entry =>
{
entry.SetAbsoluteExpiration( TimeSpan.FromSeconds( 30 ) );
return await GetData();
} ))!;
async Task<CoinCapData> GetData()
{
using var httpClient = httpClientFactory.CreateClient();
var response =
await httpClient.GetFromJsonAsync<CoinCapResponse>(
$"https://api.coincap.io/v2/rates/{id}" );
return response!.Data;
}
}
using Moq;
using NUnit.Framework;
using Microsoft.Extensions.Caching.Memory;
using System.Net.Http;
using System.Threading.Tasks;
using Moq.Protected;
using System.Threading;
using System.Net;
using System.Net.Http.Json;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
namespace CoinCapTests
{
public class CoinCapData
{
public string Id { get; set; }
public string Symbol { get; set; }
public string CurrencySymbol { get; set; }
public decimal RateUsd { get; set; }
}
public class CoinCapResponse
{
public CoinCapData Data { get; set; }
}
[TestFixture]
public class CoinCapServiceTests
{
private Mock<IMemoryCache> _memoryCacheMock;
private Mock<IHttpClientFactory> _httpClientFactoryMock;
private CoinCapService _service;
[SetUp]
public void Setup()
{
_memoryCacheMock = new Mock<IMemoryCache>();
_httpClientFactoryMock = new Mock<IHttpClientFactory>();
_service = new CoinCapService(_memoryCacheMock.Object, _httpClientFactoryMock.Object);
}
[Test]
public async Task GetCurrencyData_ReturnsCachedData_WhenDataExistsInCache()
{
// Arrange
var coinCapData = new CoinCapData { Id = "bitcoin", Symbol = "BTC", RateUsd = 50000.0M };
object cachedData = coinCapData;
_memoryCacheMock.Setup(mc => mc.GetOrCreateAsync(It.IsAny<object>(), It.IsAny<Func<ICacheEntry, Task<CoinCapData>>>()))
.ReturnsAsync(coinCapData);
// Act
var result = await _service.GetCurrencyData("bitcoin");
// Assert
Assert.IsNotNull(result);
Assert.AreEqual(coinCapData, result);
_memoryCacheMock.Verify(mc => mc.GetOrCreateAsync(It.IsAny<object>(), It.IsAny<Func<ICacheEntry, Task<CoinCapData>>>()), Times.Once);
}
[Test]
public async Task GetCurrencyData_FetchesDataFromApiAndCaches_WhenCacheMiss()
{
// Arrange
var coinCapData = new CoinCapData { Id = "bitcoin", Symbol = "BTC", RateUsd = 50000.0M };
var coinCapResponse = new CoinCapResponse { Data = coinCapData };
var apiResponse = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent(JsonConvert.SerializeObject(coinCapResponse))
};
// Mock HttpClient and HttpClientFactory
var httpMessageHandlerMock = new Mock<HttpMessageHandler>();
httpMessageHandlerMock.Protected()
.Setup<Task<HttpResponseMessage>>(
"SendAsync",
ItExpr.IsAny<HttpRequestMessage>(),
ItExpr.IsAny<CancellationToken>())
.ReturnsAsync(apiResponse);
var httpClient = new HttpClient(httpMessageHandlerMock.Object);
_httpClientFactoryMock.Setup(factory => factory.CreateClient(It.IsAny<string>())).Returns(httpClient);
// Mock cache miss by returning null for GetOrCreateAsync
CoinCapData cachedData = null;
_memoryCacheMock.Setup(mc => mc.GetOrCreateAsync(It.IsAny<object>(), It.IsAny<Func<ICacheEntry, Task<CoinCapData>>>()))
.Returns<ICacheEntry, Func<ICacheEntry, Task<CoinCapData>>>((key, func) => func(It.IsAny<ICacheEntry>()));
// Act
var result = await _service.GetCurrencyData("bitcoin");
// Assert
Assert.IsNotNull(result);
Assert.AreEqual("bitcoin", result.Id);
Assert.AreEqual("BTC", result.Symbol);
Assert.AreEqual(50000.0M, result.RateUsd);
// Verify cache miss and HTTP request
_memoryCacheMock.Verify(mc => mc.GetOrCreateAsync(It.IsAny<object>(), It.IsAny<Func<ICacheEntry, Task<CoinCapData>>>()), Times.Once);
httpMessageHandlerMock.Protected().Verify(
"SendAsync",
Times.Once(),
ItExpr.IsAny<HttpRequestMessage>(),
ItExpr.IsAny<CancellationToken>());
}
}
public class CoinCapService
{
private readonly IMemoryCache memoryCache;
private readonly IHttpClientFactory httpClientFactory;
public CoinCapService(IMemoryCache memoryCache, IHttpClientFactory httpClientFactory)
{
this.memoryCache = memoryCache;
this.httpClientFactory = httpClientFactory;
}
public async Task<CoinCapData> GetCurrencyData(string id)
{
return (await memoryCache.GetOrCreateAsync(
$"{this.GetType().Name}.GetCurrencyData({id})",
_ => GetData()))!;
async Task<CoinCapData> GetData()
{
using var httpClient = httpClientFactory.CreateClient();
var response = await httpClient.GetFromJsonAsync<CoinCapResponse>($"https://api.coincap.io/v2/rates/{id}");
return response!.Data;
}
}
}
}