Repository navigation
Expand file tree
/
Copy pathCachedUserServiceTests.cs
More file actions
48 lines (40 loc) · 1.68 KB
/
Copy pathCachedUserServiceTests.cs
File metadata and controls
48 lines (40 loc) · 1.68 KB
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
using DistributedCache.Infrastructure;
using DistributedCache.Models;
using DistributedCache.Services;
using Microsoft.Extensions.Caching.Distributed;
using Moq;
namespace DistributedCache.Tests;
public class CachedUserServiceTests
{
private static readonly IReadOnlyList<User> Users =
[new User { Id = 1, Email = "leanne@example.com" }];
[Fact]
public async Task GetUsersAsync_WhenCacheExists_DoesNotCallUsersApi()
{
var usersApi = new Mock<IUsersApiClient>();
var cache = new Mock<ICacheProvider>();
cache.Setup(x => x.GetFromCacheAsync<IReadOnlyList<User>>(CacheKeys.Users))
.ReturnsAsync(Users);
var service = new CachedUserService(new UserService(usersApi.Object), cache.Object);
var result = await service.GetUsersAsync();
Assert.Same(Users, result);
usersApi.Verify(x => x.GetUsersAsync(), Times.Never);
}
[Fact]
public async Task GetUsersAsync_WhenCacheIsEmpty_LoadsAndCachesUsers()
{
var usersApi = new Mock<IUsersApiClient>();
usersApi.Setup(x => x.GetUsersAsync()).ReturnsAsync(Users);
var cache = new Mock<ICacheProvider>();
cache.Setup(x => x.GetFromCacheAsync<IReadOnlyList<User>>(CacheKeys.Users))
.ReturnsAsync((IReadOnlyList<User>?)null);
var service = new CachedUserService(new UserService(usersApi.Object), cache.Object);
var result = await service.GetUsersAsync();
Assert.Same(Users, result);
usersApi.Verify(x => x.GetUsersAsync(), Times.Once);
cache.Verify(x => x.SetCacheAsync(
CacheKeys.Users,
Users,
It.IsAny<DistributedCacheEntryOptions>()), Times.Once);
}
}