1 // Copyright 2023 The Chromium Authors 2 // Use of this source code is governed by a BSD-style license that can be 3 // found in the LICENSE file. 4 5 package org.chromium.base.supplier; 6 7 import static org.junit.Assert.assertEquals; 8 import static org.junit.Assert.assertNull; 9 10 import androidx.test.filters.SmallTest; 11 12 import org.junit.Test; 13 import org.junit.runner.RunWith; 14 15 import org.chromium.base.test.BaseRobolectricTestRunner; 16 17 import java.util.concurrent.atomic.AtomicInteger; 18 19 /** Unit tests for {@link SyncOneshotSupplierImpl}. */ 20 @RunWith(BaseRobolectricTestRunner.class) 21 public class SyncOneshotSupplierImplTest { 22 private SyncOneshotSupplierImpl<Integer> mSupplier = new SyncOneshotSupplierImpl<>(); 23 24 private AtomicInteger mValue1 = new AtomicInteger(); 25 private AtomicInteger mValue2 = new AtomicInteger(); 26 27 @Test 28 @SmallTest testGet()29 public void testGet() { 30 final int expectedValue = 5; 31 assertNull(mSupplier.get()); 32 mSupplier.set(expectedValue); 33 assertEquals(expectedValue, (int) mSupplier.get()); 34 } 35 36 @Test 37 @SmallTest testSet()38 public void testSet() { 39 final int expectedValue = 5; 40 assertNull(mSupplier.onAvailable(mValue1::set)); 41 assertNull(mSupplier.onAvailable(mValue2::set)); 42 43 assertEquals(0, mValue1.get()); 44 assertEquals(0, mValue2.get()); 45 46 mSupplier.set(expectedValue); 47 48 assertEquals(expectedValue, mValue1.get()); 49 assertEquals(expectedValue, mValue2.get()); 50 } 51 52 @Test 53 @SmallTest testSetBeforeOnAvailable()54 public void testSetBeforeOnAvailable() { 55 final int expectedValue = 10; 56 mSupplier.set(expectedValue); 57 58 assertEquals(expectedValue, (int) mSupplier.onAvailable(mValue1::set)); 59 assertEquals(expectedValue, (int) mSupplier.onAvailable(mValue2::set)); 60 61 assertEquals(expectedValue, mValue1.get()); 62 assertEquals(expectedValue, mValue2.get()); 63 } 64 65 @Test 66 @SmallTest testSetInterleaved()67 public void testSetInterleaved() { 68 final int expectedValue = 20; 69 assertNull(mSupplier.onAvailable(mValue1::set)); 70 71 mSupplier.set(expectedValue); 72 assertEquals(expectedValue, mValue1.get()); 73 74 assertEquals(expectedValue, (int) mSupplier.onAvailable(mValue2::set)); 75 76 assertEquals(expectedValue, mValue1.get()); 77 assertEquals(expectedValue, mValue2.get()); 78 } 79 } 80