-
Notifications
You must be signed in to change notification settings - Fork 0
/
ConcurrentDictionaryTests.cs
93 lines (77 loc) · 2.73 KB
/
ConcurrentDictionaryTests.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
using NUnit.Framework;
using System;
using System.Collections.Concurrent;
namespace ConcurrentDictionaryTests
{
public class CacheKeys
{
public string Key { get; set; }
public DateTime Expiration { get; set; }
public CacheKeys(string key, DateTime expiration)
{
Key = key;
Expiration = expiration;
}
}
[TestFixture]
public class ConcurrentDictionaryUnitTest
{
private ConcurrentDictionary<string, CacheKeys> _cacheDictionary;
[SetUp]
public void Setup()
{
// Initialize the dictionary before each test
_cacheDictionary = new ConcurrentDictionary<string, CacheKeys>();
}
[Test]
public void AddOrUpdate_Item_ShouldBeAdded()
{
// Arrange
var cacheKey = new CacheKeys("Key1", DateTime.UtcNow.AddMinutes(5));
// Act
var result = _cacheDictionary.AddOrUpdate("Key1", cacheKey, (key, oldValue) => cacheKey);
// Assert
Assert.AreEqual(cacheKey, result);
Assert.IsTrue(_cacheDictionary.ContainsKey("Key1"));
Assert.AreEqual("Key1", _cacheDictionary["Key1"].Key);
}
[Test]
public void TryGetValue_ItemExists_ShouldReturnTrue()
{
// Arrange
var cacheKey = new CacheKeys("Key1", DateTime.UtcNow.AddMinutes(5));
_cacheDictionary.TryAdd("Key1", cacheKey);
// Act
var success = _cacheDictionary.TryGetValue("Key1", out var retrievedCacheKey);
// Assert
Assert.IsTrue(success);
Assert.AreEqual(cacheKey, retrievedCacheKey);
}
[Test]
public void TryRemove_ItemExists_ShouldBeRemoved()
{
// Arrange
var cacheKey = new CacheKeys("Key1", DateTime.UtcNow.AddMinutes(5));
_cacheDictionary.TryAdd("Key1", cacheKey);
// Act
var success = _cacheDictionary.TryRemove("Key1", out var removedCacheKey);
// Assert
Assert.IsTrue(success);
Assert.AreEqual(cacheKey, removedCacheKey);
Assert.IsFalse(_cacheDictionary.ContainsKey("Key1"));
}
[Test]
public void Count_ShouldReturnCorrectCount()
{
// Arrange
var cacheKey1 = new CacheKeys("Key1", DateTime.UtcNow.AddMinutes(5));
var cacheKey2 = new CacheKeys("Key2", DateTime.UtcNow.AddMinutes(10));
_cacheDictionary.TryAdd("Key1", cacheKey1);
_cacheDictionary.TryAdd("Key2", cacheKey2);
// Act
var count = _cacheDictionary.Count;
// Assert
Assert.AreEqual(2, count);
}
}
}