Merge branch 'master' of https://github.com/fluxw42/java-design-patterns into fluxw42-master

Conflicts:
	monostate/src/main/java/com/iluwatar/monostate/LoadBalancer.java
This commit is contained in:
Ilkka Seppala 2015-12-26 12:36:38 +02:00
commit 30bc25b5bf
31 changed files with 1104 additions and 59 deletions

View File

@ -32,5 +32,10 @@
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
</project>

View File

@ -30,9 +30,9 @@ public class CakeBakingServiceImpl implements CakeBakingService {
@Override
public void bakeNewCake(CakeInfo cakeInfo) throws CakeBakingException {
List<CakeToppingInfo> allToppings = getAvailableToppings();
List<CakeToppingInfo> matchingToppings =
allToppings.stream().filter((t) -> t.name.equals(cakeInfo.cakeToppingInfo.name))
List<CakeTopping> allToppings = getAvailableToppingEntities();
List<CakeTopping> matchingToppings =
allToppings.stream().filter((t) -> t.getName().equals(cakeInfo.cakeToppingInfo.name))
.collect(Collectors.toList());
if (matchingToppings.isEmpty()) {
throw new CakeBakingException(String.format("Topping %s is not available",
@ -50,7 +50,7 @@ public class CakeBakingServiceImpl implements CakeBakingService {
}
}
CakeToppingDao toppingBean = context.getBean(CakeToppingDao.class);
CakeTopping topping = toppingBean.findOne(matchingToppings.iterator().next().id.get());
CakeTopping topping = toppingBean.findOne(matchingToppings.iterator().next().getId());
CakeDao cakeBean = context.getBean(CakeDao.class);
Cake cake = new Cake();
cake.setTopping(topping);

View File

@ -43,7 +43,7 @@ public class CakeInfo {
@Override
public String toString() {
return String.format("CakeInfo id=%d topping=%s layers=%s totalCalories=%d", id.get(),
return String.format("CakeInfo id=%d topping=%s layers=%s totalCalories=%d", id.orElse(-1L),
cakeToppingInfo, cakeLayerInfos, calculateTotalCalories());
}
}

View File

@ -33,6 +33,6 @@ public class CakeLayerInfo {
@Override
public String toString() {
return String.format("CakeLayerInfo id=%d name=%s calories=%d", id.get(), name, calories);
return String.format("CakeLayerInfo id=%d name=%s calories=%d", id.orElse(-1L), name, calories);
}
}

View File

@ -58,7 +58,7 @@ public class CakeTopping {
@Override
public String toString() {
return String.format("id=%s name=%s calories=%d", name, calories);
return String.format("id=%s name=%s calories=%d", id, name, calories);
}
public Cake getCake() {

View File

@ -33,6 +33,6 @@ public class CakeToppingInfo {
@Override
public String toString() {
return String.format("CakeToppingInfo id=%d name=%s calories=%d", id.get(), name, calories);
return String.format("CakeToppingInfo id=%d name=%s calories=%d", id.orElse(-1L), name, calories);
}
}

View File

@ -0,0 +1,30 @@
package com.iluwatar.layers;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
/**
* Date: 12/15/15 - 7:57 PM
*
* @author Jeroen Meulemeester
*/
public class CakeBakingExceptionTest {
@Test
public void testConstructor() throws Exception {
final CakeBakingException exception = new CakeBakingException();
assertNull(exception.getMessage());
assertNull(exception.getCause());
}
@Test
public void testConstructorWithMessage() throws Exception {
final String expectedMessage = "message";
final CakeBakingException exception = new CakeBakingException(expectedMessage);
assertEquals(expectedMessage, exception.getMessage());
assertNull(exception.getCause());
}
}

View File

@ -0,0 +1,159 @@
package com.iluwatar.layers;
import org.junit.Test;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
/**
* Date: 12/15/15 - 9:55 PM
*
* @author Jeroen Meulemeester
*/
public class CakeBakingServiceImplTest {
@Test
public void testLayers() throws CakeBakingException {
final CakeBakingServiceImpl service = new CakeBakingServiceImpl();
final List<CakeLayerInfo> initialLayers = service.getAvailableLayers();
assertNotNull(initialLayers);
assertTrue(initialLayers.isEmpty());
service.saveNewLayer(new CakeLayerInfo("Layer1", 1000));
service.saveNewLayer(new CakeLayerInfo("Layer2", 2000));
final List<CakeLayerInfo> availableLayers = service.getAvailableLayers();
assertNotNull(availableLayers);
assertEquals(2, availableLayers.size());
for (final CakeLayerInfo layer : availableLayers) {
assertNotNull(layer.id);
assertNotNull(layer.name);
assertNotNull(layer.toString());
assertTrue(layer.calories > 0);
}
}
@Test
public void testToppings() throws CakeBakingException {
final CakeBakingServiceImpl service = new CakeBakingServiceImpl();
final List<CakeToppingInfo> initialToppings = service.getAvailableToppings();
assertNotNull(initialToppings);
assertTrue(initialToppings.isEmpty());
service.saveNewTopping(new CakeToppingInfo("Topping1", 1000));
service.saveNewTopping(new CakeToppingInfo("Topping2", 2000));
final List<CakeToppingInfo> availableToppings = service.getAvailableToppings();
assertNotNull(availableToppings);
assertEquals(2, availableToppings.size());
for (final CakeToppingInfo topping : availableToppings) {
assertNotNull(topping.id);
assertNotNull(topping.name);
assertNotNull(topping.toString());
assertTrue(topping.calories > 0);
}
}
@Test
public void testBakeCakes() throws CakeBakingException {
final CakeBakingServiceImpl service = new CakeBakingServiceImpl();
final List<CakeInfo> initialCakes = service.getAllCakes();
assertNotNull(initialCakes);
assertTrue(initialCakes.isEmpty());
final CakeToppingInfo topping1 = new CakeToppingInfo("Topping1", 1000);
final CakeToppingInfo topping2 = new CakeToppingInfo("Topping2", 2000);
service.saveNewTopping(topping1);
service.saveNewTopping(topping2);
final CakeLayerInfo layer1 = new CakeLayerInfo("Layer1", 1000);
final CakeLayerInfo layer2 = new CakeLayerInfo("Layer2", 2000);
final CakeLayerInfo layer3 = new CakeLayerInfo("Layer3", 2000);
service.saveNewLayer(layer1);
service.saveNewLayer(layer2);
service.saveNewLayer(layer3);
service.bakeNewCake(new CakeInfo(topping1, Arrays.asList(layer1, layer2)));
service.bakeNewCake(new CakeInfo(topping2, Collections.singletonList(layer3)));
final List<CakeInfo> allCakes = service.getAllCakes();
assertNotNull(allCakes);
assertEquals(2, allCakes.size());
for (final CakeInfo cakeInfo : allCakes) {
assertNotNull(cakeInfo.id);
assertNotNull(cakeInfo.cakeToppingInfo);
assertNotNull(cakeInfo.cakeLayerInfos);
assertNotNull(cakeInfo.toString());
assertFalse(cakeInfo.cakeLayerInfos.isEmpty());
assertTrue(cakeInfo.calculateTotalCalories() > 0);
}
}
@Test(expected = CakeBakingException.class)
public void testBakeCakeMissingTopping() throws CakeBakingException {
final CakeBakingServiceImpl service = new CakeBakingServiceImpl();
final CakeLayerInfo layer1 = new CakeLayerInfo("Layer1", 1000);
final CakeLayerInfo layer2 = new CakeLayerInfo("Layer2", 2000);
service.saveNewLayer(layer1);
service.saveNewLayer(layer2);
final CakeToppingInfo missingTopping = new CakeToppingInfo("Topping1", 1000);
service.bakeNewCake(new CakeInfo(missingTopping, Arrays.asList(layer1, layer2)));
}
@Test(expected = CakeBakingException.class)
public void testBakeCakeMissingLayer() throws CakeBakingException {
final CakeBakingServiceImpl service = new CakeBakingServiceImpl();
final List<CakeInfo> initialCakes = service.getAllCakes();
assertNotNull(initialCakes);
assertTrue(initialCakes.isEmpty());
final CakeToppingInfo topping1 = new CakeToppingInfo("Topping1", 1000);
service.saveNewTopping(topping1);
final CakeLayerInfo layer1 = new CakeLayerInfo("Layer1", 1000);
service.saveNewLayer(layer1);
final CakeLayerInfo missingLayer = new CakeLayerInfo("Layer2", 2000);
service.bakeNewCake(new CakeInfo(topping1, Arrays.asList(layer1, missingLayer)));
}
@Test(expected = CakeBakingException.class)
public void testBakeCakesUsedLayer() throws CakeBakingException {
final CakeBakingServiceImpl service = new CakeBakingServiceImpl();
final List<CakeInfo> initialCakes = service.getAllCakes();
assertNotNull(initialCakes);
assertTrue(initialCakes.isEmpty());
final CakeToppingInfo topping1 = new CakeToppingInfo("Topping1", 1000);
final CakeToppingInfo topping2 = new CakeToppingInfo("Topping2", 2000);
service.saveNewTopping(topping1);
service.saveNewTopping(topping2);
final CakeLayerInfo layer1 = new CakeLayerInfo("Layer1", 1000);
final CakeLayerInfo layer2 = new CakeLayerInfo("Layer2", 2000);
service.saveNewLayer(layer1);
service.saveNewLayer(layer2);
service.bakeNewCake(new CakeInfo(topping1, Arrays.asList(layer1, layer2)));
service.bakeNewCake(new CakeInfo(topping2, Collections.singletonList(layer2)));
}
}

View File

@ -0,0 +1,97 @@
package com.iluwatar.layers;
import org.junit.Test;
import java.util.HashSet;
import java.util.Set;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
/**
* Date: 12/15/15 - 8:02 PM
*
* @author Jeroen Meulemeester
*/
public class CakeTest {
@Test
public void testSetId() {
final Cake cake = new Cake();
assertNull(cake.getId());
final Long expectedId = Long.valueOf(1234L);
cake.setId(expectedId);
assertEquals(expectedId, cake.getId());
}
@Test
public void testSetTopping() {
final Cake cake = new Cake();
assertNull(cake.getTopping());
final CakeTopping expectedTopping = new CakeTopping("DummyTopping", 1000);
cake.setTopping(expectedTopping);
assertEquals(expectedTopping, cake.getTopping());
}
@Test
public void testSetLayers() {
final Cake cake = new Cake();
assertNotNull(cake.getLayers());
assertTrue(cake.getLayers().isEmpty());
final Set<CakeLayer> expectedLayers = new HashSet<>();
expectedLayers.add(new CakeLayer("layer1", 1000));
expectedLayers.add(new CakeLayer("layer2", 2000));
expectedLayers.add(new CakeLayer("layer3", 3000));
cake.setLayers(expectedLayers);
assertEquals(expectedLayers, cake.getLayers());
}
@Test
public void testAddLayer() {
final Cake cake = new Cake();
assertNotNull(cake.getLayers());
assertTrue(cake.getLayers().isEmpty());
final Set<CakeLayer> initialLayers = new HashSet<>();
initialLayers.add(new CakeLayer("layer1", 1000));
initialLayers.add(new CakeLayer("layer2", 2000));
cake.setLayers(initialLayers);
assertEquals(initialLayers, cake.getLayers());
final CakeLayer newLayer = new CakeLayer("layer3", 3000);
cake.addLayer(newLayer);
final Set<CakeLayer> expectedLayers = new HashSet<>();
expectedLayers.addAll(initialLayers);
expectedLayers.addAll(initialLayers);
expectedLayers.add(newLayer);
assertEquals(expectedLayers, cake.getLayers());
}
@Test
public void testToString() {
final CakeTopping topping = new CakeTopping("topping", 20);
topping.setId(2345L);
final CakeLayer layer = new CakeLayer("layer", 100);
layer.setId(3456L);
final Cake cake = new Cake();
cake.setId(1234L);
cake.setTopping(topping);
cake.addLayer(layer);
final String expected = "id=1234 topping=id=2345 name=topping calories=20 " +
"layers=[id=3456 name=layer calories=100]";
assertEquals(expected, cake.toString());
}
}

View File

@ -0,0 +1,48 @@
package com.iluwatar.layers;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyZeroInteractions;
import static org.mockito.Mockito.when;
/**
* Date: 12/15/15 - 10:04 PM
*
* @author Jeroen Meulemeester
*/
public class CakeViewImplTest extends StdOutTest {
/**
* Verify if the cake view renders the expected result
*/
@Test
public void testRender() {
final List<CakeLayerInfo> layers = new ArrayList<>();
layers.add(new CakeLayerInfo("layer1", 1000));
layers.add(new CakeLayerInfo("layer2", 2000));
layers.add(new CakeLayerInfo("layer3", 3000));
final List<CakeInfo> cakes = new ArrayList<>();
final CakeInfo cake = new CakeInfo(new CakeToppingInfo("topping", 1000), layers);
cakes.add(cake);
final CakeBakingService bakingService = mock(CakeBakingService.class);
when(bakingService.getAllCakes()).thenReturn(cakes);
final CakeViewImpl cakeView = new CakeViewImpl(bakingService);
verifyZeroInteractions(getStdOutMock());
cakeView.render();
verify(getStdOutMock(), times(1)).println(cake);
}
}

View File

@ -0,0 +1,54 @@
package com.iluwatar.layers;
import org.junit.After;
import org.junit.Before;
import java.io.PrintStream;
import static org.mockito.Mockito.mock;
/**
* Date: 12/10/15 - 8:37 PM
*
* @author Jeroen Meulemeester
*/
public abstract class StdOutTest {
/**
* The mocked standard out {@link PrintStream}, required since the actions of the views don't have
* any influence on any other accessible objects, except for writing to std-out using {@link
* System#out}
*/
private final PrintStream stdOutMock = mock(PrintStream.class);
/**
* Keep the original std-out so it can be restored after the test
*/
private final PrintStream stdOutOrig = System.out;
/**
* Inject the mocked std-out {@link PrintStream} into the {@link System} class before each test
*/
@Before
public void setUp() {
System.setOut(this.stdOutMock);
}
/**
* Removed the mocked std-out {@link PrintStream} again from the {@link System} class
*/
@After
public void tearDown() {
System.setOut(this.stdOutOrig);
}
/**
* Get the mocked stdOut {@link PrintStream}
*
* @return The stdOut print stream mock, renewed before each test
*/
final PrintStream getStdOutMock() {
return this.stdOutMock;
}
}

View File

@ -0,0 +1,41 @@
package com.iluwatar.lazy.loading;
import org.junit.Test;
import static junit.framework.Assert.assertNotNull;
import static junit.framework.Assert.assertSame;
import static junit.framework.TestCase.assertNull;
/**
* Date: 12/19/15 - 11:58 AM
*
* @author Jeroen Meulemeester
*/
public abstract class AbstractHolderTest {
/**
* Get the internal state of the holder value
*
* @return The internal value
*/
abstract Heavy getInternalHeavyValue() throws Exception;
/**
* Request a lazy loaded {@link Heavy} object from the holder.
*
* @return The lazy loaded {@link Heavy} object
*/
abstract Heavy getHeavy() throws Exception;
/**
* This test shows that the heavy field is not instantiated until the method getHeavy is called
*/
@Test(timeout = 3000)
public void testGetHeavy() throws Exception {
assertNull(getInternalHeavyValue());
assertNotNull(getHeavy());
assertNotNull(getInternalHeavyValue());
assertSame(getHeavy(), getInternalHeavyValue());
}
}

View File

@ -0,0 +1,26 @@
package com.iluwatar.lazy.loading;
import java.lang.reflect.Field;
/**
* Date: 12/19/15 - 12:05 PM
*
* @author Jeroen Meulemeester
*/
public class HolderNaiveTest extends AbstractHolderTest {
private final HolderNaive holder = new HolderNaive();
@Override
Heavy getInternalHeavyValue() throws Exception {
final Field holderField = HolderNaive.class.getDeclaredField("heavy");
holderField.setAccessible(true);
return (Heavy) holderField.get(this.holder);
}
@Override
Heavy getHeavy() {
return holder.getHeavy();
}
}

View File

@ -1,45 +1,26 @@
package com.iluwatar.lazy.loading;
import org.junit.Test;
import java.lang.reflect.Field;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
/**
* Using reflection this test shows that the heavy field is not instantiated until the method
* getHeavy is called
* Date: 12/19/15 - 12:19 PM
*
* Created by jones on 11/10/2015.
* @author Jeroen Meulemeester
*/
public class HolderThreadSafeTest {
public class HolderThreadSafeTest extends AbstractHolderTest {
@Test
public void test() throws IllegalAccessException {
HolderThreadSafe hts = new HolderThreadSafe();
private final HolderThreadSafe holder = new HolderThreadSafe();
{
// first call is null
Field[] ff = HolderThreadSafe.class.getDeclaredFields();
for (Field f : ff) {
f.setAccessible(true);
}
assertNull(ff[0].get(hts));
}
// now it is lazily loaded
hts.getHeavy();
{
// now it is not null - call via reflection so that the test is the same before and after
Field[] ff = HolderThreadSafe.class.getDeclaredFields();
for (Field f : ff) {
f.setAccessible(true);
}
assertNotNull(ff[0].get(hts));
}
@Override
Heavy getInternalHeavyValue() throws Exception {
final Field holderField = HolderThreadSafe.class.getDeclaredField("heavy");
holderField.setAccessible(true);
return (Heavy) holderField.get(this.holder);
}
}
@Override
Heavy getHeavy() throws Exception {
return this.holder.getHeavy();
}
}

View File

@ -0,0 +1,40 @@
package com.iluwatar.lazy.loading;
import java.lang.reflect.Field;
import java.util.function.Supplier;
/**
* Date: 12/19/15 - 12:27 PM
*
* @author Jeroen Meulemeester
*/
public class Java8HolderTest extends AbstractHolderTest {
private final Java8Holder holder = new Java8Holder();
@Override
Heavy getInternalHeavyValue() throws Exception {
final Field holderField = Java8Holder.class.getDeclaredField("heavy");
holderField.setAccessible(true);
final Supplier<Heavy> supplier = (Supplier<Heavy>) holderField.get(this.holder);
final Class<? extends Supplier> supplierClass = supplier.getClass();
// This is a little fishy, but I don't know another way to test this:
// The lazy holder is at first a lambda, but gets replaced with a new supplier after loading ...
if (supplierClass.isLocalClass()) {
final Field instanceField = supplierClass.getDeclaredField("heavyInstance");
instanceField.setAccessible(true);
return (Heavy) instanceField.get(supplier);
} else {
return null;
}
}
@Override
Heavy getHeavy() throws Exception {
return holder.getHeavy();
}
}

View File

@ -14,5 +14,10 @@
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,41 @@
package com.iluwatar.mediator;
import org.junit.Test;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.verifyZeroInteractions;
/**
* Date: 12/19/15 - 10:00 PM
*
* @author Jeroen Meulemeester
*/
public class PartyImplTest {
/**
* Verify if a member is notified when it's joining a party. Generate an action and see if the
* other member gets it. Also check members don't get their own actions.
*/
@Test
public void testPartyAction() {
final PartyMember partyMember1 = mock(PartyMember.class);
final PartyMember partyMember2 = mock(PartyMember.class);
final PartyImpl party = new PartyImpl();
party.addMember(partyMember1);
party.addMember(partyMember2);
verify(partyMember1).joinedParty(party);
verify(partyMember2).joinedParty(party);
party.act(partyMember1, Action.GOLD);
verifyZeroInteractions(partyMember1);
verify(partyMember2).partyAction(Action.GOLD);
verifyNoMoreInteractions(partyMember1, partyMember2);
}
}

View File

@ -0,0 +1,128 @@
package com.iluwatar.mediator;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import java.io.PrintStream;
import java.util.Arrays;
import java.util.Collection;
import java.util.function.Supplier;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.verifyZeroInteractions;
/**
* Date: 12/19/15 - 10:13 PM
*
* @author Jeroen Meulemeester
*/
@RunWith(Parameterized.class)
public class PartyMemberTest {
@Parameterized.Parameters
public static Collection<Supplier<PartyMember>[]> data() {
return Arrays.asList(
new Supplier[]{Hobbit::new},
new Supplier[]{Hunter::new},
new Supplier[]{Rogue::new},
new Supplier[]{Wizard::new}
);
}
/**
* The mocked standard out {@link PrintStream}, required since some actions on a {@link
* PartyMember} have any influence on any other accessible objects, except for writing to std-out
* using {@link System#out}
*/
private final PrintStream stdOutMock = mock(PrintStream.class);
/**
* Keep the original std-out so it can be restored after the test
*/
private final PrintStream stdOutOrig = System.out;
/**
* Inject the mocked std-out {@link PrintStream} into the {@link System} class before each test
*/
@Before
public void setUp() {
System.setOut(this.stdOutMock);
}
/**
* Removed the mocked std-out {@link PrintStream} again from the {@link System} class
*/
@After
public void tearDown() {
System.setOut(this.stdOutOrig);
}
/**
* The factory, used to create a new instance of the tested party member
*/
private final Supplier<PartyMember> memberSupplier;
/**
* Create a new test instance, using the given {@link PartyMember} factory
*
* @param memberSupplier The party member factory
*/
public PartyMemberTest(final Supplier<PartyMember> memberSupplier) {
this.memberSupplier = memberSupplier;
}
/**
* Verify if a party action triggers the correct output to the std-Out
*/
@Test
public void testPartyAction() {
final PartyMember member = this.memberSupplier.get();
for (final Action action : Action.values()) {
member.partyAction(action);
verify(this.stdOutMock).println(member.toString() + " " + action.getDescription());
}
verifyNoMoreInteractions(this.stdOutMock);
}
/**
* Verify if a member action triggers the expected interactions with the party class
*/
@Test
public void testAct() {
final PartyMember member = this.memberSupplier.get();
member.act(Action.GOLD);
verifyZeroInteractions(this.stdOutMock);
final Party party = mock(Party.class);
member.joinedParty(party);
verify(this.stdOutMock).println(member.toString() + " joins the party");
for (final Action action : Action.values()) {
member.act(action);
verify(this.stdOutMock).println(member.toString() + " " + action.toString());
verify(party).act(member, action);
}
verifyNoMoreInteractions(party, this.stdOutMock);
}
/**
* Verify if {@link PartyMember#toString()} generate the expected output
*/
@Test
public void testToString() throws Exception {
final PartyMember member = this.memberSupplier.get();
final Class<? extends PartyMember> memberClass = member.getClass();
assertEquals(memberClass.getSimpleName(), member.toString());
}
}

View File

@ -0,0 +1,75 @@
package com.iluwatar.memento;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
/**
* Date: 12/20/15 - 10:08 AM
*
* @author Jeroen Meulemeester
*/
public class StarTest {
/**
* Verify the stages of a dying sun, without going back in time
*/
@Test
public void testTimePasses() {
final Star star = new Star(StarType.SUN, 1, 2);
assertEquals("sun age: 1 years mass: 2 tons", star.toString());
star.timePasses();
assertEquals("red giant age: 2 years mass: 16 tons", star.toString());
star.timePasses();
assertEquals("white dwarf age: 4 years mass: 128 tons", star.toString());
star.timePasses();
assertEquals("supernova age: 8 years mass: 1024 tons", star.toString());
star.timePasses();
assertEquals("dead star age: 16 years mass: 8192 tons", star.toString());
star.timePasses();
assertEquals("dead star age: 64 years mass: 0 tons", star.toString());
star.timePasses();
assertEquals("dead star age: 256 years mass: 0 tons", star.toString());
}
/**
* Verify some stage of a dying sun, but go back in time to test the memento
*/
@Test
public void testSetMemento() {
final Star star = new Star(StarType.SUN, 1, 2);
final StarMemento firstMemento = star.getMemento();
assertEquals("sun age: 1 years mass: 2 tons", star.toString());
star.timePasses();
final StarMemento secondMemento = star.getMemento();
assertEquals("red giant age: 2 years mass: 16 tons", star.toString());
star.timePasses();
final StarMemento thirdMemento = star.getMemento();
assertEquals("white dwarf age: 4 years mass: 128 tons", star.toString());
star.timePasses();
assertEquals("supernova age: 8 years mass: 1024 tons", star.toString());
star.setMemento(thirdMemento);
assertEquals("white dwarf age: 4 years mass: 128 tons", star.toString());
star.timePasses();
assertEquals("supernova age: 8 years mass: 1024 tons", star.toString());
star.setMemento(secondMemento);
assertEquals("red giant age: 2 years mass: 16 tons", star.toString());
star.setMemento(firstMemento);
assertEquals("sun age: 1 years mass: 2 tons", star.toString());
}
}

View File

@ -14,5 +14,10 @@
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,100 @@
package com.iluwatar.model.view.controller;
import org.junit.Test;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.verifyZeroInteractions;
/**
* Date: 12/20/15 - 2:19 PM
*
* @author Jeroen Meulemeester
*/
public class GiantControllerTest {
/**
* Verify if the controller passes the health level through to the model and vice versa
*/
@Test
public void testSetHealth() {
final GiantModel model = mock(GiantModel.class);
final GiantView view = mock(GiantView.class);
final GiantController controller = new GiantController(model, view);
verifyZeroInteractions(model, view);
for (final Health health : Health.values()) {
controller.setHealth(health);
verify(model).setHealth(health);
verifyZeroInteractions(view);
}
controller.getHealth();
verify(model).getHealth();
verifyNoMoreInteractions(model, view);
}
/**
* Verify if the controller passes the fatigue level through to the model and vice versa
*/
@Test
public void testSetFatigue() {
final GiantModel model = mock(GiantModel.class);
final GiantView view = mock(GiantView.class);
final GiantController controller = new GiantController(model, view);
verifyZeroInteractions(model, view);
for (final Fatigue fatigue : Fatigue.values()) {
controller.setFatigue(fatigue);
verify(model).setFatigue(fatigue);
verifyZeroInteractions(view);
}
controller.getFatigue();
verify(model).getFatigue();
verifyNoMoreInteractions(model, view);
}
/**
* Verify if the controller passes the nourishment level through to the model and vice versa
*/
@Test
public void testSetNourishment() {
final GiantModel model = mock(GiantModel.class);
final GiantView view = mock(GiantView.class);
final GiantController controller = new GiantController(model, view);
verifyZeroInteractions(model, view);
for (final Nourishment nourishment : Nourishment.values()) {
controller.setNourishment(nourishment);
verify(model).setNourishment(nourishment);
verifyZeroInteractions(view);
}
controller.getNourishment();
verify(model).getNourishment();
verifyNoMoreInteractions(model, view);
}
@Test
public void testUpdateView() {
final GiantModel model = mock(GiantModel.class);
final GiantView view = mock(GiantView.class);
final GiantController controller = new GiantController(model, view);
verifyZeroInteractions(model, view);
controller.updateView();
verify(view).displayGiant(model);
verifyNoMoreInteractions(model, view);
}
}

View File

@ -0,0 +1,56 @@
package com.iluwatar.model.view.controller;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
/**
* Date: 12/20/15 - 2:10 PM
*
* @author Jeroen Meulemeester
*/
public class GiantModelTest {
/**
* Verify if the health value is set properly though the constructor and setter
*/
@Test
public void testSetHealth() {
final GiantModel model = new GiantModel(Health.HEALTHY, Fatigue.ALERT, Nourishment.SATURATED);
assertEquals(Health.HEALTHY, model.getHealth());
for (final Health health : Health.values()) {
model.setHealth(health);
assertEquals(health, model.getHealth());
assertEquals("The giant looks " + health.toString() + ", alert and saturated.", model.toString());
}
}
/**
* Verify if the fatigue level is set properly though the constructor and setter
*/
@Test
public void testSetFatigue() {
final GiantModel model = new GiantModel(Health.HEALTHY, Fatigue.ALERT, Nourishment.SATURATED);
assertEquals(Fatigue.ALERT, model.getFatigue());
for (final Fatigue fatigue : Fatigue.values()) {
model.setFatigue(fatigue);
assertEquals(fatigue, model.getFatigue());
assertEquals("The giant looks healthy, " + fatigue.toString() + " and saturated.", model.toString());
}
}
/**
* Verify if the nourishment level is set properly though the constructor and setter
*/
@Test
public void testSetNourishment() {
final GiantModel model = new GiantModel(Health.HEALTHY, Fatigue.ALERT, Nourishment.SATURATED);
assertEquals(Nourishment.SATURATED, model.getNourishment());
for (final Nourishment nourishment : Nourishment.values()) {
model.setNourishment(nourishment);
assertEquals(nourishment, model.getNourishment());
assertEquals("The giant looks healthy, alert and " + nourishment.toString() + ".", model.toString());
}
}
}

View File

@ -0,0 +1,64 @@
package com.iluwatar.model.view.controller;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.PrintStream;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
/**
* Date: 12/20/15 - 2:04 PM
*
* @author Jeroen Meulemeester
*/
public class GiantViewTest {
/**
* The mocked standard out {@link PrintStream}, required since the actions of the views don't have
* any influence on any other accessible objects, except for writing to std-out using {@link
* System#out}
*/
private final PrintStream stdOutMock = mock(PrintStream.class);
/**
* Keep the original std-out so it can be restored after the test
*/
private final PrintStream stdOutOrig = System.out;
/**
* Inject the mocked std-out {@link PrintStream} into the {@link System} class before each test
*/
@Before
public void setUp() {
System.setOut(this.stdOutMock);
}
/**
* Removed the mocked std-out {@link PrintStream} again from the {@link System} class
*/
@After
public void tearDown() {
System.setOut(this.stdOutOrig);
}
/**
* Verify if the {@link GiantView} does what it has to do: Print the {@link GiantModel} to the
* standard out stream, nothing more, nothing less.
*/
@Test
public void testDisplayGiant() {
final GiantView view = new GiantView();
final GiantModel model = mock(GiantModel.class);
view.displayGiant(model);
verify(this.stdOutMock).println(model);
verifyNoMoreInteractions(model, this.stdOutMock);
}
}

View File

@ -0,0 +1,18 @@
package com.iluwatar.model.view.presenter;
import org.junit.Test;
/**
*
* Application test
*
*/
public class AppTest {
@Test
public void test() {
String[] args = {};
App.main(args);
}
}

View File

@ -0,0 +1,24 @@
package com.iluwatar.model.view.presenter;
import org.junit.Test;
import java.io.FileNotFoundException;
import java.io.IOException;
import static org.junit.Assert.*;
/**
* Date: 12/21/15 - 12:12 PM
*
* @author Jeroen Meulemeester
*/
public class FileLoaderTest {
@Test
public void testLoadData() throws Exception {
final FileLoader fileLoader = new FileLoader();
fileLoader.setFileName("non-existing-file");
assertNull(fileLoader.loadData());
}
}

View File

@ -14,5 +14,10 @@
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
</project>

View File

@ -28,8 +28,8 @@ public class App {
public static void main(String[] args) {
LoadBalancer loadBalancer1 = new LoadBalancer();
LoadBalancer loadBalancer2 = new LoadBalancer();
loadBalancer1.serverequest(new Request("Hello"));
loadBalancer2.serverequest(new Request("Hello World"));
loadBalancer1.serverRequest(new Request("Hello"));
loadBalancer2.serverRequest(new Request("Hello World"));
}
}

View File

@ -45,7 +45,7 @@ public class LoadBalancer {
/**
* Handle request
*/
public void serverequest(Request request) {
public void serverRequest(Request request) {
if (lastServedId >= servers.size()) {
lastServedId = 0;
}

View File

@ -28,7 +28,7 @@ public class Server {
return port;
}
public final void serve(Request request) {
public void serve(Request request) {
System.out.println("Server ID " + id + " associated to host : " + getHost() + " and Port "
+ getPort() + " Processed request with value " + request.value);
}

View File

@ -5,22 +5,10 @@ import org.junit.Test;
public class AppTest {
@Test
public void testSameStateAmonstAllInstances() {
LoadBalancer balancer = new LoadBalancer();
LoadBalancer balancer2 = new LoadBalancer();
balancer.addServer(new Server("localhost", 8085, 6));
// Both should have the same number of servers.
Assert.assertTrue(balancer.getNoOfServers() == balancer2.getNoOfServers());
// Both Should have the same LastServedId
Assert.assertTrue(balancer.getLastServedId() == balancer2.getLastServedId());
}
@Test
public void testMain() {
String[] args = {};
App.main(args);
Assert.assertTrue(LoadBalancer.getLastServedId() == 2);
}
}

View File

@ -0,0 +1,55 @@
package com.iluwatar.monostate;
import org.junit.Assert;
import org.junit.Test;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.verifyZeroInteractions;
import static org.mockito.Mockito.when;
/**
* Date: 12/21/15 - 12:26 PM
*
* @author Jeroen Meulemeester
*/
public class LoadBalancerTest {
@Test
public void testSameStateAmongstAllInstances() {
final LoadBalancer firstBalancer = new LoadBalancer();
final LoadBalancer secondBalancer = new LoadBalancer();
firstBalancer.addServer(new Server("localhost", 8085, 6));
// Both should have the same number of servers.
Assert.assertTrue(firstBalancer.getNoOfServers() == secondBalancer.getNoOfServers());
// Both Should have the same LastServedId
Assert.assertTrue(firstBalancer.getLastServedId() == secondBalancer.getLastServedId());
}
@Test
public void testServe() {
final Server server = mock(Server.class);
when(server.getHost()).thenReturn("testhost");
when(server.getPort()).thenReturn(1234);
doNothing().when(server).serve(any(Request.class));
final LoadBalancer loadBalancer = new LoadBalancer();
loadBalancer.addServer(server);
verifyZeroInteractions(server);
final Request request = new Request("test");
for (int i = 0; i < loadBalancer.getNoOfServers() * 2; i++) {
loadBalancer.serverRequest(request);
}
verify(server, times(2)).serve(request);
verifyNoMoreInteractions(server);
}
}