|
| 1 | +package com.thealgorithms.datastructures.caches; |
| 2 | + |
| 3 | +import static org.junit.jupiter.api.Assertions.*; |
| 4 | + |
| 5 | +import org.junit.jupiter.api.BeforeEach; |
| 6 | +import org.junit.jupiter.api.Test; |
| 7 | + |
| 8 | +public class ARCCacheTest { |
| 9 | + private ARCCache<Integer, String> cache; |
| 10 | + |
| 11 | + @BeforeEach |
| 12 | + public void setUp() { |
| 13 | + cache = new ARCCache<>(3); // Set capacity to 3 for testing purposes |
| 14 | + } |
| 15 | + |
| 16 | + @Test |
| 17 | + public void testPutAndGet() { |
| 18 | + cache.put(1, "Value1"); |
| 19 | + cache.put(2, "Value2"); |
| 20 | + cache.put(3, "Value3"); |
| 21 | + |
| 22 | + assertEquals("Value1", cache.get(1)); |
| 23 | + assertEquals("Value2", cache.get(2)); |
| 24 | + assertEquals("Value3", cache.get(3)); |
| 25 | + } |
| 26 | + |
| 27 | + @Test |
| 28 | + public void testEviction() { |
| 29 | + cache.put(1, "Value1"); |
| 30 | + cache.put(2, "Value2"); |
| 31 | + cache.put(3, "Value3"); |
| 32 | + |
| 33 | + cache.put(4, "Value4"); // This should evict key 1 |
| 34 | + |
| 35 | + assertNull(cache.get(1)); // Key 1 should have been evicted |
| 36 | + assertEquals("Value2", cache.get(2)); // Other keys should still be present |
| 37 | + assertEquals("Value3", cache.get(3)); |
| 38 | + assertEquals("Value4", cache.get(4)); |
| 39 | + } |
| 40 | + |
| 41 | + @Test |
| 42 | + public void nullKeysAndValues() { |
| 43 | + cache.put(null, "Value1"); |
| 44 | + cache.put(2, null); |
| 45 | + |
| 46 | + assertEquals("Value1", cache.get(null)); |
| 47 | + assertNull(cache.get(2)); |
| 48 | + assertNull(cache.get(6)); |
| 49 | + } |
| 50 | + |
| 51 | + @Test |
| 52 | + public void testRepeatedGet() { |
| 53 | + cache.put(1, "Value1"); |
| 54 | + |
| 55 | + // Repeated get calls should not affect eviction |
| 56 | + cache.get(1); |
| 57 | + cache.get(1); |
| 58 | + cache.get(1); |
| 59 | + |
| 60 | + // Adding new elements should still evict old ones |
| 61 | + cache.put(2, "Value2"); |
| 62 | + cache.put(3, "Value3"); |
| 63 | + cache.put(4, "Value4"); |
| 64 | + |
| 65 | + assertNull(cache.get(2)); // Key 2 should have been evicted |
| 66 | + assertEquals("Value1", cache.get(1)); // Other keys should still be present |
| 67 | + assertEquals("Value3", cache.get(3)); // Other keys should still be present |
| 68 | + } |
| 69 | +} |
0 commit comments