Add proper tests for flyweight pattern

This commit is contained in:
Jeroen Meulemeester 2015-12-13 11:42:25 +01:00
parent 3dc370e2d1
commit ca14e8ddad
2 changed files with 59 additions and 0 deletions

View File

@ -1,6 +1,7 @@
package com.iluwatar.flyweight; package com.iluwatar.flyweight;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections;
import java.util.List; import java.util.List;
/** /**
@ -39,6 +40,24 @@ public class AlchemistShop {
bottomShelf.add(factory.createPotion(PotionType.HOLY_WATER)); bottomShelf.add(factory.createPotion(PotionType.HOLY_WATER));
} }
/**
* Get a read-only list of all the items on the top shelf
*
* @return The top shelf potions
*/
public final List<Potion> getTopShelf() {
return Collections.unmodifiableList(this.topShelf);
}
/**
* Get a read-only list of all the items on the bottom shelf
*
* @return The bottom shelf potions
*/
public final List<Potion> getBottomShelf() {
return Collections.unmodifiableList(this.bottomShelf);
}
public void enumerate() { public void enumerate() {
System.out.println("Enumerating top shelf potions\n"); System.out.println("Enumerating top shelf potions\n");

View File

@ -0,0 +1,40 @@
package com.iluwatar.flyweight;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
/**
* Date: 12/12/15 - 10:54 PM
*
* @author Jeroen Meulemeester
*/
public class AlchemistShopTest {
@Test
public void testShop() throws Exception {
final AlchemistShop shop = new AlchemistShop();
final List<Potion> bottomShelf = shop.getBottomShelf();
assertNotNull(bottomShelf);
assertEquals(5, bottomShelf.size());
final List<Potion> topShelf = shop.getTopShelf();
assertNotNull(topShelf);
assertEquals(8, topShelf.size());
final List<Potion> allPotions = new ArrayList<>();
allPotions.addAll(topShelf);
allPotions.addAll(bottomShelf);
// There are 13 potion instances, but only 5 unique instance types
assertEquals(13, allPotions.size());
assertEquals(5, allPotions.stream().map(System::identityHashCode).distinct().count());
}
}