### Question:
Items { public static <T> T chooseWeighted( Collection<Weighted<T>> items, SourceOfRandomness random) { if (items.size() == 1) return items.iterator().next().item; int range = items.stream().mapToInt(i -> i.weight).sum(); int sample = random.nextInt(range); int threshold = 0; for (Weighted<T> each : items) { threshold += each.weight; if (sample < threshold) return each.item; } throw new AssertionError( String.format("sample = %d, range = %d", sample, range)); } private  Items(); @SuppressWarnings("unchecked") static T choose(Collection<T> items, SourceOfRandomness random); static T chooseWeighted(
        Collection<Weighted<T>> items,
        SourceOfRandomness random);  }### Answer:
@Test public void choosingWeightedFromEmptyCollection() { thrown.expect(AssertionError.class); thrown.expectMessage("sample = 0, range = 0"); Items.chooseWeighted(emptyList(), random); }
@Test public void singleWeightedItem() { when(random.nextInt(2)).thenReturn(1); assertEquals("a", Items.chooseWeighted(singletonList(first), random)); }
@Test public void choosingFirstOfManyWeightedItems() { when(random.nextInt(9)).thenReturn(0).thenReturn(1); assertEquals("a", Items.chooseWeighted(asList(first, second, third), random)); assertEquals("a", Items.chooseWeighted(asList(first, second, third), random)); }
@Test public void choosingMiddleOfManyWeightedItems() { when(random.nextInt(9)).thenReturn(2).thenReturn(3).thenReturn(4); assertEquals("b", Items.chooseWeighted(asList(first, second, third), random)); assertEquals("b", Items.chooseWeighted(asList(first, second, third), random)); assertEquals("b", Items.chooseWeighted(asList(first, second, third), random)); }
@Test public void choosingLastOfManyWeightedItems() { when(random.nextInt(9)).thenReturn(5).thenReturn(6).thenReturn(7).thenReturn(8); assertEquals("c", Items.chooseWeighted(asList(first, second, third), random)); assertEquals("c", Items.chooseWeighted(asList(first, second, third), random)); assertEquals("c", Items.chooseWeighted(asList(first, second, third), random)); assertEquals("c", Items.chooseWeighted(asList(first, second, third), random)); }