#502 Adjusted tests for logger introduction

This commit is contained in:
daniel-bryla 2016-11-04 11:47:06 +01:00
parent 27d6d500bc
commit e138163c4f
56 changed files with 1447 additions and 1602 deletions

View File

@ -22,16 +22,18 @@
*/
package com.iluwatar.decorator;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.AppenderBase;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.LoggerFactory;
import java.io.PrintStream;
import java.util.LinkedList;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.*;
import static org.mockito.internal.verification.VerificationModeFactory.times;
/**
* Date: 12/7/15 - 7:26 PM
@ -40,31 +42,16 @@ import static org.mockito.internal.verification.VerificationModeFactory.times;
*/
public class TrollTest {
/**
* The mocked standard out stream, required since the actions don't have any influence on other
* objects, except for writing to the std-out using {@link System#out}
*/
private final PrintStream stdOutMock = mock(PrintStream.class);
private InMemoryAppender appender;
/**
* 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);
appender = new InMemoryAppender(Troll.class);
}
/**
* Removed the mocked std-out {@link PrintStream} again from the {@link System} class
*/
@After
public void tearDown() {
System.setOut(this.stdOutOrig);
appender.stop();
}
@Test
@ -73,12 +60,34 @@ public class TrollTest {
assertEquals(10, troll.getAttackPower());
troll.attack();
verify(this.stdOutMock, times(1)).println(eq("The troll swings at you with a club!"));
assertEquals("The troll swings at you with a club!", appender.getLastMessage());
troll.fleeBattle();
verify(this.stdOutMock, times(1)).println(eq("The troll shrieks in horror and runs away!"));
assertEquals("The troll shrieks in horror and runs away!", appender.getLastMessage());
verifyNoMoreInteractions(this.stdOutMock);
assertEquals(2, appender.getLogSize());
}
}
private class InMemoryAppender extends AppenderBase<ILoggingEvent> {
private List<ILoggingEvent> log = new LinkedList<>();
public InMemoryAppender(Class clazz) {
((Logger) LoggerFactory.getLogger(clazz)).addAppender(this);
start();
}
@Override
protected void append(ILoggingEvent eventObject) {
log.add(eventObject);
}
public String getLastMessage() {
return log.get(log.size() - 1).getMessage();
}
public int getLogSize() {
return log.size();
}
}
}

View File

@ -22,28 +22,44 @@
*/
package com.iluwatar.delegation.simple;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.AppenderBase;
import com.iluwatar.delegation.simple.printers.CanonPrinter;
import com.iluwatar.delegation.simple.printers.EpsonPrinter;
import com.iluwatar.delegation.simple.printers.HpPrinter;
import org.junit.Rule;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.contrib.java.lang.system.SystemOutRule;
import org.slf4j.LoggerFactory;
import java.util.LinkedList;
import java.util.List;
import static org.junit.Assert.assertEquals;
public class DelegateTest {
private static final String MESSAGE = "Test Message Printed";
private InMemoryAppender appender;
@Rule
public final SystemOutRule systemOutRule = new SystemOutRule().enableLog();
@Before
public void setUp() {
appender = new InMemoryAppender();
}
@After
public void tearDown() {
appender.stop();
}
private static final String MESSAGE = "Test Message Printed";
@Test
public void testCanonPrinter() throws Exception {
PrinterController printerController = new PrinterController(new CanonPrinter());
printerController.print(MESSAGE);
assertEquals("Canon Printer : Test Message Printed", systemOutRule.getLog());
assertEquals("Canon Printer : Test Message Printed", appender.getLastMessage());
}
@Test
@ -51,7 +67,7 @@ public class DelegateTest {
PrinterController printerController = new PrinterController(new HpPrinter());
printerController.print(MESSAGE);
assertEquals("HP Printer : Test Message Printed", systemOutRule.getLog());
assertEquals("HP Printer : Test Message Printed", appender.getLastMessage());
}
@Test
@ -59,7 +75,30 @@ public class DelegateTest {
PrinterController printerController = new PrinterController(new EpsonPrinter());
printerController.print(MESSAGE);
assertEquals("Epson Printer : Test Message Printed", systemOutRule.getLog());
assertEquals("Epson Printer : Test Message Printed", appender.getLastMessage());
}
private class InMemoryAppender extends AppenderBase<ILoggingEvent> {
private List<ILoggingEvent> log = new LinkedList<>();
public InMemoryAppender() {
((Logger) LoggerFactory.getLogger("root")).addAppender(this);
start();
}
@Override
protected void append(ILoggingEvent eventObject) {
log.add(eventObject);
}
public String getLastMessage() {
return log.get(log.size() - 1).getFormattedMessage();
}
public int getLogSize() {
return log.size();
}
}
}

View File

@ -22,18 +22,31 @@
*/
package com.iluwatar.dependency.injection;
import com.iluwatar.dependency.injection.utils.InMemoryAppender;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.junit.Assert.assertEquals;
/**
* Date: 12/10/15 - 8:40 PM
*
* @author Jeroen Meulemeester
*/
public class AdvancedWizardTest extends StdOutTest {
public class AdvancedWizardTest {
private InMemoryAppender appender;
@Before
public void setUp() {
appender = new InMemoryAppender(Tobacco.class);
}
@After
public void tearDown() {
appender.stop();
}
/**
* Test if the {@link AdvancedWizard} smokes whatever instance of {@link Tobacco} is passed to him
@ -51,12 +64,13 @@ public class AdvancedWizardTest extends StdOutTest {
advancedWizard.smoke();
// Verify if the wizard is smoking the correct tobacco ...
verify(getStdOutMock(), times(1)).println("AdvancedWizard smoking " + tobacco.getClass().getSimpleName());
assertEquals("AdvancedWizard smoking " + tobacco.getClass().getSimpleName(), appender.getLastMessage());
// ... and nothing else is happening.
verifyNoMoreInteractions(getStdOutMock());
}
// ... and nothing else is happening.
assertEquals(tobaccos.length, appender.getLogSize());
}
}
}

View File

@ -25,19 +25,31 @@ package com.iluwatar.dependency.injection;
import com.google.inject.AbstractModule;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.iluwatar.dependency.injection.utils.InMemoryAppender;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.junit.Assert.assertEquals;
/**
* Date: 12/10/15 - 8:57 PM
*
* @author Jeroen Meulemeester
*/
public class GuiceWizardTest extends StdOutTest {
public class GuiceWizardTest {
private InMemoryAppender appender;
@Before
public void setUp() {
appender = new InMemoryAppender(Tobacco.class);
}
@After
public void tearDown() {
appender.stop();
}
/**
* Test if the {@link GuiceWizard} smokes whatever instance of {@link Tobacco} is passed to him
@ -55,12 +67,11 @@ public class GuiceWizardTest extends StdOutTest {
guiceWizard.smoke();
// Verify if the wizard is smoking the correct tobacco ...
verify(getStdOutMock(), times(1)).println("GuiceWizard smoking " + tobacco.getClass().getSimpleName());
// ... and nothing else is happening.
verifyNoMoreInteractions(getStdOutMock());
assertEquals("GuiceWizard smoking " + tobacco.getClass().getSimpleName(), appender.getLastMessage());
}
// ... and nothing else is happening.
assertEquals(tobaccos.length, appender.getLogSize());
}
/**
@ -89,12 +100,11 @@ public class GuiceWizardTest extends StdOutTest {
guiceWizard.smoke();
// Verify if the wizard is smoking the correct tobacco ...
verify(getStdOutMock(), times(1)).println("GuiceWizard smoking " + tobaccoClass.getSimpleName());
// ... and nothing else is happening.
verifyNoMoreInteractions(getStdOutMock());
assertEquals("GuiceWizard smoking " + tobaccoClass.getSimpleName(), appender.getLastMessage());
}
// ... and nothing else is happening.
assertEquals(tobaccos.length, appender.getLogSize());
}
}
}

View File

@ -22,16 +22,31 @@
*/
package com.iluwatar.dependency.injection;
import com.iluwatar.dependency.injection.utils.InMemoryAppender;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import static org.mockito.Mockito.*;
import static org.junit.Assert.assertEquals;
/**
* Date: 12/10/15 - 8:26 PM
*
* @author Jeroen Meulemeester
*/
public class SimpleWizardTest extends StdOutTest {
public class SimpleWizardTest {
private InMemoryAppender appender;
@Before
public void setUp() {
appender = new InMemoryAppender(Tobacco.class);
}
@After
public void tearDown() {
appender.stop();
}
/**
* Test if the {@link SimpleWizard} does the only thing it can do: Smoke it's {@link
@ -41,8 +56,8 @@ public class SimpleWizardTest extends StdOutTest {
public void testSmoke() {
final SimpleWizard simpleWizard = new SimpleWizard();
simpleWizard.smoke();
verify(getStdOutMock(), times(1)).println("SimpleWizard smoking OldTobyTobacco");
verifyNoMoreInteractions(getStdOutMock());
assertEquals("SimpleWizard smoking OldTobyTobacco", appender.getLastMessage());
assertEquals(1, appender.getLogSize());
}
}
}

View File

@ -1,75 +0,0 @@
/**
* The MIT License
* Copyright (c) 2014 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.dependency.injection;
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 wizard 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,54 @@
/**
* The MIT License
* Copyright (c) 2014 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.dependency.injection.utils;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.AppenderBase;
import org.slf4j.LoggerFactory;
import java.util.LinkedList;
import java.util.List;
public class InMemoryAppender extends AppenderBase<ILoggingEvent> {
private List<ILoggingEvent> log = new LinkedList<>();
public InMemoryAppender(Class clazz) {
((Logger) LoggerFactory.getLogger(clazz)).addAppender(this);
start();
}
@Override
protected void append(ILoggingEvent eventObject) {
log.add(eventObject);
}
public String getLastMessage() {
return log.get(log.size() - 1).getFormattedMessage();
}
public int getLogSize() {
return log.size();
}
}

View File

@ -22,24 +22,23 @@
*/
package com.iluwatar.doublechecked.locking;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.AppenderBase;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.slf4j.LoggerFactory;
import java.io.PrintStream;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import static junit.framework.Assert.assertTrue;
import static junit.framework.TestCase.assertEquals;
import static org.junit.Assert.assertNotNull;
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.junit.Assert.assertTrue;
/**
* Date: 12/10/15 - 9:34 PM
@ -48,31 +47,16 @@ import static org.mockito.Mockito.verifyNoMoreInteractions;
*/
public class InventoryTest {
/**
* The mocked standard out {@link PrintStream}, used to verify a steady increasing size of the
* {@link Inventory} while adding items from multiple threads concurrently
*/
private final PrintStream stdOutMock = mock(PrintStream.class);
private InMemoryAppender appender;
/**
* 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);
appender = new InMemoryAppender(Inventory.class);
}
/**
* Removed the mocked std-out {@link PrintStream} again from the {@link System} class
*/
@After
public void tearDown() {
System.setOut(this.stdOutOrig);
appender.stop();
}
/**
@ -112,21 +96,32 @@ public class InventoryTest {
assertNotNull(items);
assertEquals(INVENTORY_SIZE, items.size());
// Capture all stdOut messages ...
final ArgumentCaptor<String> stdOutCaptor = ArgumentCaptor.forClass(String.class);
verify(this.stdOutMock, times(INVENTORY_SIZE)).println(stdOutCaptor.capture());
// ... verify if we got all 1000
final List<String> values = stdOutCaptor.getAllValues();
assertEquals(INVENTORY_SIZE, values.size());
assertEquals(INVENTORY_SIZE, appender.getLogSize());
// ... and check if the inventory size is increasing continuously
for (int i = 0; i < values.size(); i++) {
assertNotNull(values.get(i));
assertTrue(values.get(i).contains("items.size()=" + (i + 1)));
for (int i = 0; i < items.size(); i++) {
assertTrue(appender.log.get(i).getFormattedMessage().contains("items.size()=" + (i + 1)));
}
verifyNoMoreInteractions(this.stdOutMock);
}
}
private class InMemoryAppender extends AppenderBase<ILoggingEvent> {
private List<ILoggingEvent> log = new LinkedList<>();
public InMemoryAppender(Class clazz) {
((Logger) LoggerFactory.getLogger(clazz)).addAppender(this);
start();
}
@Override
protected void append(ILoggingEvent eventObject) {
log.add(eventObject);
}
public int getLogSize() {
return log.size();
}
}
}

View File

@ -22,17 +22,9 @@
*/
package com.iluwatar.doubledispatch;
import org.junit.After;
import org.junit.Before;
import java.io.PrintStream;
import java.util.Objects;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
/**
* Date: 12/10/15 - 8:37 PM
@ -41,43 +33,6 @@ import static org.mockito.Mockito.verifyNoMoreInteractions;
*/
public abstract class CollisionTest<O extends GameObject> {
/**
* The mocked standard out {@link PrintStream}, required if some of the actions on the tested
* object don't have a direct 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;
}
/**
* Get the tested object
*
@ -106,9 +61,6 @@ public abstract class CollisionTest<O extends GameObject> {
tested.collision(other);
verify(getStdOutMock(), times(1)).println(description);
verifyNoMoreInteractions(getStdOutMock());
testOnFire(other, tested, otherOnFire);
testDamaged(other, tested, otherDamaged);
@ -129,8 +81,8 @@ public abstract class CollisionTest<O extends GameObject> {
final String targetName = target.getClass().getSimpleName();
final String otherName = other.getClass().getSimpleName();
final String errorMessage = expectTargetOnFire
? "Expected [" + targetName + "] to be on fire after colliding with [" + otherName + "] but it was not!"
final String errorMessage = expectTargetOnFire
? "Expected [" + targetName + "] to be on fire after colliding with [" + otherName + "] but it was not!"
: "Expected [" + targetName + "] not to be on fire after colliding with [" + otherName + "] but it was!";
assertEquals(errorMessage, expectTargetOnFire, target.isOnFire());
@ -149,7 +101,7 @@ public abstract class CollisionTest<O extends GameObject> {
final String otherName = other.getClass().getSimpleName();
final String errorMessage = expectedDamage
? "Expected [" + targetName + "] to be damaged after colliding with [" + otherName + "] but it was not!"
? "Expected [" + targetName + "] to be damaged after colliding with [" + otherName + "] but it was not!"
: "Expected [" + targetName + "] not to be damaged after colliding with [" + otherName + "] but it was!";
assertEquals(errorMessage, expectedDamage, target.isDamaged());

View File

@ -22,17 +22,18 @@
*/
package com.iluwatar.event.aggregator;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.AppenderBase;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.LoggerFactory;
import java.io.PrintStream;
import java.util.LinkedList;
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.verifyNoMoreInteractions;
import static org.junit.Assert.assertEquals;
/**
* Date: 12/12/15 - 3:04 PM
@ -41,31 +42,16 @@ import static org.mockito.Mockito.verifyNoMoreInteractions;
*/
public class KingJoffreyTest {
/**
* The mocked standard out {@link PrintStream}, required since {@link KingJoffrey} does nothing
* except for writing to std-out using {@link System#out}
*/
private final PrintStream stdOutMock = mock(PrintStream.class);
private InMemoryAppender appender;
/**
* 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);
appender = new InMemoryAppender(KingJoffrey.class);
}
/**
* Removed the mocked std-out {@link PrintStream} again from the {@link System} class
*/
@After
public void tearDown() {
System.setOut(this.stdOutOrig);
appender.stop();
}
/**
@ -75,15 +61,38 @@ public class KingJoffreyTest {
public void testOnEvent() {
final KingJoffrey kingJoffrey = new KingJoffrey();
for (final Event event : Event.values()) {
verifyZeroInteractions(this.stdOutMock);
for (int i = 0; i < Event.values().length; ++i) {
assertEquals(i, appender.getLogSize());
Event event = Event.values()[i];
kingJoffrey.onEvent(event);
final String expectedMessage = "Received event from the King's Hand: " + event.toString();
verify(this.stdOutMock, times(1)).println(expectedMessage);
verifyNoMoreInteractions(this.stdOutMock);
assertEquals(expectedMessage, appender.getLastMessage());
assertEquals(i + 1, appender.getLogSize());
}
}
}
private class InMemoryAppender extends AppenderBase<ILoggingEvent> {
private List<ILoggingEvent> log = new LinkedList<>();
public InMemoryAppender(Class clazz) {
((Logger) LoggerFactory.getLogger(clazz)).addAppender(this);
start();
}
@Override
protected void append(ILoggingEvent eventObject) {
log.add(eventObject);
}
public String getLastMessage() {
return log.get(log.size() - 1).getFormattedMessage();
}
public int getLogSize() {
return log.size();
}
}
}

View File

@ -22,17 +22,19 @@
*/
package com.iluwatar.facade;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.AppenderBase;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.LoggerFactory;
import java.io.PrintStream;
import java.util.LinkedList;
import java.util.List;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.internal.verification.VerificationModeFactory.times;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
/**
* Date: 12/9/15 - 9:40 PM
@ -41,35 +43,19 @@ import static org.mockito.internal.verification.VerificationModeFactory.times;
*/
public class DwarvenGoldmineFacadeTest {
/**
* The mocked standard out {@link PrintStream}, required since the actions on the gold mine facade
* 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);
private InMemoryAppender appender;
/**
* 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);
appender = new InMemoryAppender();
}
/**
* Removed the mocked std-out {@link PrintStream} again from the {@link System} class
*/
@After
public void tearDown() {
System.setOut(this.stdOutOrig);
appender.stop();
}
/**
/**
* Test a complete day cycle in the gold mine by executing all three different steps: {@link
* DwarvenGoldmineFacade#startNewDay()}, {@link DwarvenGoldmineFacade#digOutGold()} and {@link
* DwarvenGoldmineFacade#endDay()}.
@ -82,44 +68,68 @@ public class DwarvenGoldmineFacadeTest {
goldMine.startNewDay();
// On the start of a day, all workers should wake up ...
verify(this.stdOutMock, times(1)).println(eq("Dwarf gold digger wakes up."));
verify(this.stdOutMock, times(1)).println(eq("Dwarf cart operator wakes up."));
verify(this.stdOutMock, times(1)).println(eq("Dwarven tunnel digger wakes up."));
assertTrue(appender.logContains("Dwarf gold digger wakes up."));
assertTrue(appender.logContains("Dwarf cart operator wakes up."));
assertTrue(appender.logContains("Dwarven tunnel digger wakes up."));
// ... and go to the mine
verify(this.stdOutMock, times(1)).println(eq("Dwarf gold digger goes to the mine."));
verify(this.stdOutMock, times(1)).println(eq("Dwarf cart operator goes to the mine."));
verify(this.stdOutMock, times(1)).println(eq("Dwarven tunnel digger goes to the mine."));
assertTrue(appender.logContains("Dwarf gold digger goes to the mine."));
assertTrue(appender.logContains("Dwarf cart operator goes to the mine."));
assertTrue(appender.logContains("Dwarven tunnel digger goes to the mine."));
// No other actions were invoked, so the workers shouldn't have done (printed) anything else
verifyNoMoreInteractions(this.stdOutMock);
assertEquals(6, appender.getLogSize());
// Now do some actual work, start digging gold!
goldMine.digOutGold();
// Since we gave the dig command, every worker should be doing it's job ...
verify(this.stdOutMock, times(1)).println(eq("Dwarf gold digger digs for gold."));
verify(this.stdOutMock, times(1)).println(eq("Dwarf cart operator moves gold chunks out of the mine."));
verify(this.stdOutMock, times(1)).println(eq("Dwarven tunnel digger creates another promising tunnel."));
assertTrue(appender.logContains("Dwarf gold digger digs for gold."));
assertTrue(appender.logContains("Dwarf cart operator moves gold chunks out of the mine."));
assertTrue(appender.logContains("Dwarven tunnel digger creates another promising tunnel."));
// Again, they shouldn't be doing anything else.
verifyNoMoreInteractions(this.stdOutMock);
assertEquals(9, appender.getLogSize());
// Enough gold, lets end the day.
goldMine.endDay();
// Check if the workers go home ...
verify(this.stdOutMock, times(1)).println(eq("Dwarf gold digger goes home."));
verify(this.stdOutMock, times(1)).println(eq("Dwarf cart operator goes home."));
verify(this.stdOutMock, times(1)).println(eq("Dwarven tunnel digger goes home."));
assertTrue(appender.logContains("Dwarf gold digger goes home."));
assertTrue(appender.logContains("Dwarf cart operator goes home."));
assertTrue(appender.logContains("Dwarven tunnel digger goes home."));
// ... and go to sleep. We need well rested workers the next day :)
verify(this.stdOutMock, times(1)).println(eq("Dwarf gold digger goes to sleep."));
verify(this.stdOutMock, times(1)).println(eq("Dwarf cart operator goes to sleep."));
verify(this.stdOutMock, times(1)).println(eq("Dwarven tunnel digger goes to sleep."));
assertTrue(appender.logContains("Dwarf gold digger goes to sleep."));
assertTrue(appender.logContains("Dwarf cart operator goes to sleep."));
assertTrue(appender.logContains("Dwarven tunnel digger goes to sleep."));
// Every worker should be sleeping now, no other actions allowed
verifyNoMoreInteractions(this.stdOutMock);
assertEquals(15, appender.getLogSize());
}
private class InMemoryAppender extends AppenderBase<ILoggingEvent> {
private List<ILoggingEvent> log = new LinkedList<>();
public InMemoryAppender() {
((Logger) LoggerFactory.getLogger("root")).addAppender(this);
start();
}
@Override
protected void append(ILoggingEvent eventObject) {
log.add(eventObject);
}
public int getLogSize() {
return log.size();
}
public boolean logContains(String message) {
return log.stream().anyMatch(event -> event.getFormattedMessage().equals(message));
}
}
}

View File

@ -22,6 +22,9 @@
*/
package com.iluwatar.front.controller;
import com.iluwatar.front.controller.utils.InMemoryAppender;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
@ -30,9 +33,7 @@ import org.junit.runners.Parameterized.Parameters;
import java.util.ArrayList;
import java.util.List;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.verifyZeroInteractions;
import static org.junit.Assert.assertEquals;
/**
* Date: 12/13/15 - 1:39 PM
@ -40,7 +41,19 @@ import static org.mockito.Mockito.verifyZeroInteractions;
* @author Jeroen Meulemeester
*/
@RunWith(Parameterized.class)
public class CommandTest extends StdOutTest {
public class CommandTest {
private InMemoryAppender appender;
@Before
public void setUp() {
appender = new InMemoryAppender();
}
@After
public void tearDown() {
appender.stop();
}
@Parameters
public static List<Object[]> data() {
@ -75,10 +88,10 @@ public class CommandTest extends StdOutTest {
@Test
public void testDisplay() {
final FrontController frontController = new FrontController();
verifyZeroInteractions(getStdOutMock());
assertEquals(0, appender.getLogSize());
frontController.handleRequest(request);
verify(getStdOutMock()).println(displayMessage);
verifyNoMoreInteractions(getStdOutMock());
assertEquals(displayMessage, appender.getLastMessage());
assertEquals(1, appender.getLogSize());
}
}

View File

@ -22,6 +22,9 @@
*/
package com.iluwatar.front.controller;
import com.iluwatar.front.controller.utils.InMemoryAppender;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
@ -30,9 +33,7 @@ import org.junit.runners.Parameterized.Parameters;
import java.util.ArrayList;
import java.util.List;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.verifyZeroInteractions;
import static org.junit.Assert.assertEquals;
/**
* Date: 12/13/15 - 1:39 PM
@ -40,7 +41,19 @@ import static org.mockito.Mockito.verifyZeroInteractions;
* @author Jeroen Meulemeester
*/
@RunWith(Parameterized.class)
public class FrontControllerTest extends StdOutTest {
public class FrontControllerTest {
private InMemoryAppender appender;
@Before
public void setUp() {
appender = new InMemoryAppender();
}
@After
public void tearDown() {
appender.stop();
}
@Parameters
public static List<Object[]> data() {
@ -74,10 +87,10 @@ public class FrontControllerTest extends StdOutTest {
@Test
public void testDisplay() {
verifyZeroInteractions(getStdOutMock());
assertEquals(0, appender.getLogSize());
this.command.process();
verify(getStdOutMock()).println(displayMessage);
verifyNoMoreInteractions(getStdOutMock());
assertEquals(displayMessage, appender.getLastMessage());
assertEquals(1, appender.getLogSize());
}
}

View File

@ -1,76 +0,0 @@
/**
* The MIT License
* Copyright (c) 2014 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.front.controller;
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

@ -22,6 +22,9 @@
*/
package com.iluwatar.front.controller;
import com.iluwatar.front.controller.utils.InMemoryAppender;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
@ -30,9 +33,7 @@ import org.junit.runners.Parameterized.Parameters;
import java.util.ArrayList;
import java.util.List;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.verifyZeroInteractions;
import static org.junit.Assert.assertEquals;
/**
* Date: 12/13/15 - 1:39 PM
@ -40,7 +41,19 @@ import static org.mockito.Mockito.verifyZeroInteractions;
* @author Jeroen Meulemeester
*/
@RunWith(Parameterized.class)
public class ViewTest extends StdOutTest {
public class ViewTest {
private InMemoryAppender appender;
@Before
public void setUp() {
appender = new InMemoryAppender();
}
@After
public void tearDown() {
appender.stop();
}
@Parameters
public static List<Object[]> data() {
@ -74,10 +87,10 @@ public class ViewTest extends StdOutTest {
@Test
public void testDisplay() {
verifyZeroInteractions(getStdOutMock());
assertEquals(0, appender.getLogSize());
this.view.display();
verify(getStdOutMock()).println(displayMessage);
verifyNoMoreInteractions(getStdOutMock());
assertEquals(displayMessage, appender.getLastMessage());
assertEquals(1, appender.getLogSize());
}
}
}

View File

@ -0,0 +1,54 @@
/**
* The MIT License
* Copyright (c) 2014 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.front.controller.utils;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.AppenderBase;
import org.slf4j.LoggerFactory;
import java.util.LinkedList;
import java.util.List;
public class InMemoryAppender extends AppenderBase<ILoggingEvent> {
private List<ILoggingEvent> log = new LinkedList<>();
public InMemoryAppender() {
((Logger) LoggerFactory.getLogger("root")).addAppender(this);
start();
}
@Override
protected void append(ILoggingEvent eventObject) {
log.add(eventObject);
}
public String getLastMessage() {
return log.get(log.size() - 1).getFormattedMessage();
}
public int getLogSize() {
return log.size();
}
}

View File

@ -24,7 +24,6 @@ package com.iluwatar.hexagonal.service;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.iluwatar.hexagonal.administration.ConsoleAdministration;
import com.iluwatar.hexagonal.banking.WireTransfers;
import com.iluwatar.hexagonal.domain.LotteryNumbers;
import com.iluwatar.hexagonal.domain.LotteryService;

View File

@ -22,11 +22,19 @@
*/
package com.iluwatar.layers;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.AppenderBase;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.*;
/**
@ -34,7 +42,19 @@ import static org.mockito.Mockito.*;
*
* @author Jeroen Meulemeester
*/
public class CakeViewImplTest extends StdOutTest {
public class CakeViewImplTest {
private InMemoryAppender appender;
@Before
public void setUp() {
appender = new InMemoryAppender(CakeViewImpl.class);
}
@After
public void tearDown() {
appender.stop();
}
/**
* Verify if the cake view renders the expected result
@ -56,11 +76,34 @@ public class CakeViewImplTest extends StdOutTest {
final CakeViewImpl cakeView = new CakeViewImpl(bakingService);
verifyZeroInteractions(getStdOutMock());
assertEquals(0, appender.getLogSize());
cakeView.render();
verify(getStdOutMock(), times(1)).println(cake);
assertEquals(cake.toString(), appender.getLastMessage());
}
private class InMemoryAppender extends AppenderBase<ILoggingEvent> {
private List<ILoggingEvent> log = new LinkedList<>();
public InMemoryAppender(Class clazz) {
((Logger) LoggerFactory.getLogger(clazz)).addAppender(this);
start();
}
@Override
protected void append(ILoggingEvent eventObject) {
log.add(eventObject);
}
public String getLastMessage() {
return log.get(log.size() - 1).getFormattedMessage();
}
public int getLogSize() {
return log.size();
}
}
}

View File

@ -1,78 +0,0 @@
/**
* The MIT License
* Copyright (c) 2014 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.layers;
import org.junit.After;
import org.junit.Before;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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

@ -22,22 +22,25 @@
*/
package com.iluwatar.mediator;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.AppenderBase;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.slf4j.LoggerFactory;
import java.io.PrintStream;
import java.util.Arrays;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
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
@ -57,34 +60,6 @@ public class PartyMemberTest {
);
}
/**
* 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
*/
@ -99,6 +74,18 @@ public class PartyMemberTest {
this.memberSupplier = memberSupplier;
}
private InMemoryAppender appender;
@Before
public void setUp() {
appender = new InMemoryAppender(PartyMemberBase.class);
}
@After
public void tearDown() {
appender.stop();
}
/**
* Verify if a party action triggers the correct output to the std-Out
*/
@ -108,10 +95,10 @@ public class PartyMemberTest {
for (final Action action : Action.values()) {
member.partyAction(action);
verify(this.stdOutMock).println(member.toString() + " " + action.getDescription());
assertEquals(member.toString() + " " + action.getDescription(), appender.getLastMessage());
}
verifyNoMoreInteractions(this.stdOutMock);
assertEquals(Action.values().length, appender.getLogSize());
}
/**
@ -122,19 +109,19 @@ public class PartyMemberTest {
final PartyMember member = this.memberSupplier.get();
member.act(Action.GOLD);
verifyZeroInteractions(this.stdOutMock);
assertEquals(0, appender.getLogSize());
final Party party = mock(Party.class);
member.joinedParty(party);
verify(this.stdOutMock).println(member.toString() + " joins the party");
assertEquals(member.toString() + " joins the party", appender.getLastMessage());
for (final Action action : Action.values()) {
member.act(action);
verify(this.stdOutMock).println(member.toString() + " " + action.toString());
assertEquals(member.toString() + " " + action.toString(), appender.getLastMessage());
verify(party).act(member, action);
}
verifyNoMoreInteractions(party, this.stdOutMock);
assertEquals(Action.values().length + 1, appender.getLogSize());
}
/**
@ -147,4 +134,27 @@ public class PartyMemberTest {
assertEquals(memberClass.getSimpleName(), member.toString());
}
private class InMemoryAppender extends AppenderBase<ILoggingEvent> {
private List<ILoggingEvent> log = new LinkedList<>();
public InMemoryAppender(Class clazz) {
((Logger) LoggerFactory.getLogger(clazz)).addAppender(this);
start();
}
@Override
protected void append(ILoggingEvent eventObject) {
log.add(eventObject);
}
public int getLogSize() {
return log.size();
}
public String getLastMessage() {
return log.get(log.size() - 1).getFormattedMessage();
}
}
}

View File

@ -22,15 +22,19 @@
*/
package com.iluwatar.model.view.controller;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.AppenderBase;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.LoggerFactory;
import java.io.PrintStream;
import java.util.LinkedList;
import java.util.List;
import static org.junit.Assert.assertEquals;
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
@ -39,32 +43,16 @@ import static org.mockito.Mockito.verifyNoMoreInteractions;
*/
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);
private InMemoryAppender appender;
/**
* 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);
appender = new InMemoryAppender(GiantView.class);
}
/**
* Removed the mocked std-out {@link PrintStream} again from the {@link System} class
*/
@After
public void tearDown() {
System.setOut(this.stdOutOrig);
appender.stop();
}
/**
@ -78,9 +66,29 @@ public class GiantViewTest {
final GiantModel model = mock(GiantModel.class);
view.displayGiant(model);
verify(this.stdOutMock).println(model);
verifyNoMoreInteractions(model, this.stdOutMock);
assertEquals(model.toString(), appender.getLastMessage());
assertEquals(1, appender.getLogSize());
}
}
public class InMemoryAppender extends AppenderBase<ILoggingEvent> {
private List<ILoggingEvent> log = new LinkedList<>();
public InMemoryAppender(Class clazz) {
((Logger) LoggerFactory.getLogger(clazz)).addAppender(this);
start();
}
@Override
protected void append(ILoggingEvent eventObject) {
log.add(eventObject);
}
public String getLastMessage() {
return log.get(log.size() - 1).getMessage();
}
public int getLogSize() {
return log.size();
}
}
}

View File

@ -23,19 +23,15 @@
package com.iluwatar.nullobject;
import org.junit.Test;
import org.mockito.Mockito;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.*;
/**
* Date: 12/26/15 - 11:47 PM
*
* @author Jeroen Meulemeester
*/
public class NullNodeTest extends StdOutTest {
public class NullNodeTest {
/**
* Verify if {@link NullNode#getInstance()} actually returns the same object instance
@ -59,7 +55,6 @@ public class NullNodeTest extends StdOutTest {
@Test
public void testWalk() throws Exception {
NullNode.getInstance().walk();
Mockito.verifyZeroInteractions(getStdOutMock());
}
}
}

View File

@ -1,76 +0,0 @@
/**
* The MIT License
* Copyright (c) 2014 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.nullobject;
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 walking through the tree has no
* influence on any other accessible object, 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

@ -22,20 +22,37 @@
*/
package com.iluwatar.nullobject;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.AppenderBase;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.mockito.InOrder;
import org.mockito.Mockito;
import org.slf4j.LoggerFactory;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertSame;
import java.util.LinkedList;
import java.util.List;
import static org.junit.Assert.*;
/**
* Date: 12/26/15 - 11:44 PM
*
* @author Jeroen Meulemeester
*/
public class TreeTest extends StdOutTest {
public class TreeTest {
private InMemoryAppender appender;
@Before
public void setUp() {
appender = new InMemoryAppender();
}
@After
public void tearDown() {
appender.stop();
}
/**
* During the tests, the same tree structure will be used, shown below. End points will be
@ -79,15 +96,14 @@ public class TreeTest extends StdOutTest {
public void testWalk() {
TREE_ROOT.walk();
final InOrder inOrder = Mockito.inOrder(getStdOutMock());
inOrder.verify(getStdOutMock()).println("root");
inOrder.verify(getStdOutMock()).println("level1_a");
inOrder.verify(getStdOutMock()).println("level2_a");
inOrder.verify(getStdOutMock()).println("level3_a");
inOrder.verify(getStdOutMock()).println("level3_b");
inOrder.verify(getStdOutMock()).println("level2_b");
inOrder.verify(getStdOutMock()).println("level1_b");
inOrder.verifyNoMoreInteractions();
assertTrue(appender.logContains("root"));
assertTrue(appender.logContains("level1_a"));
assertTrue(appender.logContains("level2_a"));
assertTrue(appender.logContains("level3_a"));
assertTrue(appender.logContains("level3_b"));
assertTrue(appender.logContains("level2_b"));
assertTrue(appender.logContains("level1_b"));
assertEquals(7, appender.getLogSize());
}
@Test
@ -120,4 +136,26 @@ public class TreeTest extends StdOutTest {
assertSame(NullNode.getInstance(), level1.getLeft());
}
private class InMemoryAppender extends AppenderBase<ILoggingEvent> {
private List<ILoggingEvent> log = new LinkedList<>();
public InMemoryAppender() {
((Logger) LoggerFactory.getLogger("root")).addAppender(this);
start();
}
@Override
protected void append(ILoggingEvent eventObject) {
log.add(eventObject);
}
public boolean logContains(String message) {
return log.stream().anyMatch(event -> event.getMessage().equals(message));
}
public int getLogSize() {
return log.size();
}
}
}

View File

@ -1,76 +0,0 @@
/**
* The MIT License
* Copyright (c) 2014 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.observer;
import org.junit.After;
import org.junit.Before;
import java.io.PrintStream;
import static org.mockito.Mockito.mock;
/**
* Date: 12/27/15 - 12:16 PM
*
* @author Jeroen Meulemeester
*/
public abstract class StdOutTest {
/**
* The mocked standard out {@link PrintStream}, required since changes in the weather doesn't has
* 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
*/
protected final PrintStream getStdOutMock() {
return this.stdOutMock;
}
}

View File

@ -22,20 +22,33 @@
*/
package com.iluwatar.observer;
import com.iluwatar.observer.utils.InMemoryAppender;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.util.function.Supplier;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.verifyZeroInteractions;
import static org.junit.Assert.assertEquals;
/**
* Date: 12/27/15 - 11:44 AM
*
* @author Jeroen Meulemeester
*/
public abstract class WeatherObserverTest<O extends WeatherObserver> extends StdOutTest {
public abstract class WeatherObserverTest<O extends WeatherObserver> {
private InMemoryAppender appender;
@Before
public void setUp() {
appender = new InMemoryAppender();
}
@After
public void tearDown() {
appender.stop();
}
/**
* The observer instance factory
@ -71,11 +84,11 @@ public abstract class WeatherObserverTest<O extends WeatherObserver> extends Std
@Test
public void testObserver() {
final O observer = this.factory.get();
verifyZeroInteractions(getStdOutMock());
assertEquals(0, appender.getLogSize());
observer.update(this.weather);
verify(getStdOutMock()).println(this.response);
verifyNoMoreInteractions(getStdOutMock());
assertEquals(response, appender.getLastMessage());
assertEquals(1, appender.getLogSize());
}
}
}

View File

@ -22,9 +22,13 @@
*/
package com.iluwatar.observer;
import com.iluwatar.observer.utils.InMemoryAppender;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.mockito.InOrder;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
@ -36,7 +40,19 @@ import static org.mockito.Mockito.verifyZeroInteractions;
*
* @author Jeroen Meulemeester
*/
public class WeatherTest extends StdOutTest {
public class WeatherTest {
private InMemoryAppender appender;
@Before
public void setUp() {
appender = new InMemoryAppender(Weather.class);
}
@After
public void tearDown() {
appender.stop();
}
/**
* Add a {@link WeatherObserver}, verify if it gets notified of a weather change, remove the
@ -51,14 +67,15 @@ public class WeatherTest extends StdOutTest {
verifyZeroInteractions(observer);
weather.timePasses();
verify(getStdOutMock()).println("The weather changed to rainy.");
assertEquals("The weather changed to rainy.", appender.getLastMessage());
verify(observer).update(WeatherType.RAINY);
weather.removeObserver(observer);
weather.timePasses();
verify(getStdOutMock()).println("The weather changed to windy.");
assertEquals("The weather changed to windy.", appender.getLastMessage());
verifyNoMoreInteractions(observer, getStdOutMock());
verifyNoMoreInteractions(observer);
assertEquals(2, appender.getLogSize());
}
/**
@ -70,7 +87,7 @@ public class WeatherTest extends StdOutTest {
final Weather weather = new Weather();
weather.addObserver(observer);
final InOrder inOrder = inOrder(observer, getStdOutMock());
final InOrder inOrder = inOrder(observer);
final WeatherType[] weatherTypes = WeatherType.values();
for (int i = 1; i < 20; i++) {
weather.timePasses();
@ -80,4 +97,4 @@ public class WeatherTest extends StdOutTest {
verifyNoMoreInteractions(observer);
}
}
}

View File

@ -22,25 +22,35 @@
*/
package com.iluwatar.observer.generic;
import com.iluwatar.observer.StdOutTest;
import com.iluwatar.observer.WeatherObserver;
import com.iluwatar.observer.WeatherType;
import com.iluwatar.observer.utils.InMemoryAppender;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.mockito.InOrder;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.verifyZeroInteractions;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.*;
/**
* Date: 12/27/15 - 11:08 AM
*
* @author Jeroen Meulemeester
*/
public class GWeatherTest extends StdOutTest {
public class GWeatherTest {
private InMemoryAppender appender;
@Before
public void setUp() {
appender = new InMemoryAppender(GWeather.class);
}
@After
public void tearDown() {
appender.stop();
}
/**
* Add a {@link WeatherObserver}, verify if it gets notified of a weather change, remove the
@ -55,14 +65,15 @@ public class GWeatherTest extends StdOutTest {
verifyZeroInteractions(observer);
weather.timePasses();
verify(getStdOutMock()).println("The weather changed to rainy.");
assertEquals("The weather changed to rainy.", appender.getLastMessage());
verify(observer).update(weather, WeatherType.RAINY);
weather.removeObserver(observer);
weather.timePasses();
verify(getStdOutMock()).println("The weather changed to windy.");
assertEquals("The weather changed to windy.", appender.getLastMessage());
verifyNoMoreInteractions(observer, getStdOutMock());
verifyNoMoreInteractions(observer);
assertEquals(2, appender.getLogSize());
}
/**
@ -74,7 +85,7 @@ public class GWeatherTest extends StdOutTest {
final GWeather weather = new GWeather();
weather.addObserver(observer);
final InOrder inOrder = inOrder(observer, getStdOutMock());
final InOrder inOrder = inOrder(observer);
final WeatherType[] weatherTypes = WeatherType.values();
for (int i = 1; i < 20; i++) {
weather.timePasses();
@ -84,4 +95,4 @@ public class GWeatherTest extends StdOutTest {
verifyNoMoreInteractions(observer);
}
}
}

View File

@ -22,23 +22,34 @@
*/
package com.iluwatar.observer.generic;
import com.iluwatar.observer.StdOutTest;
import com.iluwatar.observer.WeatherType;
import com.iluwatar.observer.utils.InMemoryAppender;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.util.function.Supplier;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.verifyZeroInteractions;
import static org.junit.Assert.assertEquals;
/**
* Date: 12/27/15 - 11:44 AM
*
* @author Jeroen Meulemeester
*/
public abstract class ObserverTest<O extends Observer> extends StdOutTest {
public abstract class ObserverTest<O extends Observer> {
private InMemoryAppender appender;
@Before
public void setUp() {
appender = new InMemoryAppender();
}
@After
public void tearDown() {
appender.stop();
}
/**
* The observer instance factory
@ -74,11 +85,11 @@ public abstract class ObserverTest<O extends Observer> extends StdOutTest {
@Test
public void testObserver() {
final O observer = this.factory.get();
verifyZeroInteractions(getStdOutMock());
assertEquals(0, appender.getLogSize());
observer.update(null, this.weather);
verify(getStdOutMock()).println(this.response);
verifyNoMoreInteractions(getStdOutMock());
assertEquals(this.response, appender.getLastMessage());
assertEquals(1, appender.getLogSize());
}
}
}

View File

@ -0,0 +1,58 @@
/**
* The MIT License
* Copyright (c) 2014 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.observer.utils;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.AppenderBase;
import org.slf4j.LoggerFactory;
import java.util.LinkedList;
import java.util.List;
public class InMemoryAppender extends AppenderBase<ILoggingEvent> {
private List<ILoggingEvent> log = new LinkedList<>();
public InMemoryAppender(Class clazz) {
((Logger) LoggerFactory.getLogger(clazz)).addAppender(this);
start();
}
public InMemoryAppender() {
((Logger) LoggerFactory.getLogger("root")).addAppender(this);
start();
}
@Override
protected void append(ILoggingEvent eventObject) {
log.add(eventObject);
}
public int getLogSize() {
return log.size();
}
public String getLastMessage() {
return log.get(log.size() - 1).getFormattedMessage();
}
}

View File

@ -22,19 +22,38 @@
*/
package com.iluwatar.poison.pill;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.AppenderBase;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.mockito.InOrder;
import org.slf4j.LoggerFactory;
import java.time.LocalDateTime;
import java.util.LinkedList;
import java.util.List;
import static org.mockito.Mockito.inOrder;
import static org.junit.Assert.assertTrue;
/**
* Date: 12/27/15 - 9:45 PM
*
* @author Jeroen Meulemeester
*/
public class ConsumerTest extends StdOutTest {
public class ConsumerTest {
private InMemoryAppender appender;
@Before
public void setUp() {
appender = new InMemoryAppender(Consumer.class);
}
@After
public void tearDown() {
appender.stop();
}
@Test
public void testConsume() throws Exception {
@ -52,12 +71,9 @@ public class ConsumerTest extends StdOutTest {
new Consumer("NSA", queue).consume();
final InOrder inOrder = inOrder(getStdOutMock());
inOrder.verify(getStdOutMock()).println("Message [Hello!] from [you] received by [NSA]");
inOrder.verify(getStdOutMock()).println("Message [Hi!] from [me] received by [NSA]");
inOrder.verify(getStdOutMock()).println("Consumer NSA receive request to terminate.");
inOrder.verifyNoMoreInteractions();
assertTrue(appender.logContains("Message [Hello!] from [you] received by [NSA]"));
assertTrue(appender.logContains("Message [Hi!] from [me] received by [NSA]"));
assertTrue(appender.logContains("Consumer NSA receive request to terminate."));
}
/**
@ -75,4 +91,22 @@ public class ConsumerTest extends StdOutTest {
return msg;
}
}
private class InMemoryAppender extends AppenderBase<ILoggingEvent> {
private List<ILoggingEvent> log = new LinkedList<>();
public InMemoryAppender(Class clazz) {
((Logger) LoggerFactory.getLogger(clazz)).addAppender(this);
start();
}
@Override
protected void append(ILoggingEvent eventObject) {
log.add(eventObject);
}
public boolean logContains(String message) {
return log.stream().anyMatch(event -> event.getFormattedMessage().equals(message));
}
}
}

View File

@ -1,75 +0,0 @@
/**
* The MIT License
* Copyright (c) 2014 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.poison.pill;
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 some actions don't have any
* influence on 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

@ -22,18 +22,31 @@
*/
package com.iluwatar.privateclassdata;
import com.iluwatar.privateclassdata.utils.InMemoryAppender;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.mockito.InOrder;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.verify;
import static org.junit.Assert.assertEquals;
/**
* Date: 12/27/15 - 10:46 PM
*
* @author Jeroen Meulemeester
*/
public class ImmutableStewTest extends StdOutTest {
public class ImmutableStewTest {
private InMemoryAppender appender;
@Before
public void setUp() {
appender = new InMemoryAppender();
}
@After
public void tearDown() {
appender.stop();
}
/**
* Verify if mixing the stew doesn't change the internal state
@ -41,15 +54,14 @@ public class ImmutableStewTest extends StdOutTest {
@Test
public void testMix() {
final Stew stew = new Stew(1, 2, 3, 4);
final String message = "Mixing the stew we find: 1 potatoes, 2 carrots, 3 meat and 4 peppers";
final String expectedMessage = "Mixing the stew we find: 1 potatoes, 2 carrots, 3 meat and 4 peppers";
final InOrder inOrder = inOrder(getStdOutMock());
for (int i = 0; i < 20; i++) {
stew.mix();
inOrder.verify(getStdOutMock()).println(message);
assertEquals(expectedMessage, appender.getLastMessage());
}
inOrder.verifyNoMoreInteractions();
assertEquals(20, appender.getLogSize());
}
/**
@ -60,15 +72,12 @@ public class ImmutableStewTest extends StdOutTest {
final Stew stew = new Stew(1, 2, 3, 4);
stew.mix();
verify(getStdOutMock())
.println("Mixing the stew we find: 1 potatoes, 2 carrots, 3 meat and 4 peppers");
assertEquals("Mixing the stew we find: 1 potatoes, 2 carrots, 3 meat and 4 peppers", appender.getLastMessage());
stew.taste();
verify(getStdOutMock()).println("Tasting the stew");
assertEquals("Tasting the stew", appender.getLastMessage());
stew.mix();
verify(getStdOutMock())
.println("Mixing the stew we find: 0 potatoes, 1 carrots, 2 meat and 3 peppers");
assertEquals("Mixing the stew we find: 0 potatoes, 1 carrots, 2 meat and 3 peppers", appender.getLastMessage());
}
}
}

View File

@ -1,75 +0,0 @@
/**
* The MIT License
* Copyright (c) 2014 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.privateclassdata;
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 some actions don't have any
* influence on 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

@ -22,17 +22,31 @@
*/
package com.iluwatar.privateclassdata;
import com.iluwatar.privateclassdata.utils.InMemoryAppender;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.mockito.InOrder;
import static org.mockito.Mockito.inOrder;
import static org.junit.Assert.assertEquals;
/**
* Date: 12/27/15 - 10:46 PM
*
* @author Jeroen Meulemeester
*/
public class StewTest extends StdOutTest {
public class StewTest {
private InMemoryAppender appender;
@Before
public void setUp() {
appender = new InMemoryAppender();
}
@After
public void tearDown() {
appender.stop();
}
/**
* Verify if mixing the stew doesn't change the internal state
@ -43,13 +57,12 @@ public class StewTest extends StdOutTest {
final String expectedMessage = "Mixing the immutable stew we find: 1 potatoes, "
+ "2 carrots, 3 meat and 4 peppers";
final InOrder inOrder = inOrder(getStdOutMock());
for (int i = 0; i < 20; i++) {
stew.mix();
inOrder.verify(getStdOutMock()).println(expectedMessage);
assertEquals(expectedMessage, appender.getLastMessage());
}
inOrder.verifyNoMoreInteractions();
assertEquals(20, appender.getLogSize());
}
}
}

View File

@ -0,0 +1,53 @@
/**
* The MIT License
* Copyright (c) 2014 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.privateclassdata.utils;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.AppenderBase;
import org.slf4j.LoggerFactory;
import java.util.LinkedList;
import java.util.List;
public class InMemoryAppender extends AppenderBase<ILoggingEvent> {
private List<ILoggingEvent> log = new LinkedList<>();
public InMemoryAppender() {
((Logger) LoggerFactory.getLogger("root")).addAppender(this);
start();
}
@Override
protected void append(ILoggingEvent eventObject) {
log.add(eventObject);
}
public int getLogSize() {
return log.size();
}
public String getLastMessage() {
return log.get(log.size() - 1).getFormattedMessage();
}
}

View File

@ -23,18 +23,15 @@
package com.iluwatar.producer.consumer;
import org.junit.Test;
import org.mockito.InOrder;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.*;
/**
* Date: 12/27/15 - 11:01 PM
*
* @author Jeroen Meulemeester
*/
public class ConsumerTest extends StdOutTest {
public class ConsumerTest {
private static final int ITEM_COUNT = 5;
@ -48,14 +45,11 @@ public class ConsumerTest extends StdOutTest {
reset(queue); // Don't count the preparation above as interactions with the queue
final Consumer consumer = new Consumer("consumer", queue);
final InOrder inOrder = inOrder(getStdOutMock());
for (int id = 0; id < ITEM_COUNT; id++) {
consumer.consume();
inOrder.verify(getStdOutMock())
.println("Consumer [consumer] consume item [" + id + "] produced by [producer]");
}
inOrder.verifyNoMoreInteractions();
verify(queue, times(ITEM_COUNT)).take();
}
}

View File

@ -1,75 +0,0 @@
/**
* The MIT License
* Copyright (c) 2014 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.producer.consumer;
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 some actions don't have any
* influence on 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

@ -1,75 +0,0 @@
/**
* The MIT License
* Copyright (c) 2014 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.proxy;
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 some actions don't have any
* influence on 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

@ -22,17 +22,32 @@
*/
package com.iluwatar.proxy;
import com.iluwatar.proxy.utils.InMemoryAppender;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.mockito.InOrder;
import static org.mockito.Mockito.inOrder;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
/**
* Date: 12/28/15 - 9:18 PM
*
* @author Jeroen Meulemeester
*/
public class WizardTowerProxyTest extends StdOutTest {
public class WizardTowerProxyTest {
private InMemoryAppender appender;
@Before
public void setUp() {
appender = new InMemoryAppender();
}
@After
public void tearDown() {
appender.stop();
}
@Test
public void testEnter() throws Exception {
@ -48,13 +63,11 @@ public class WizardTowerProxyTest extends StdOutTest {
tower.enter(wizard);
}
final InOrder inOrder = inOrder(getStdOutMock());
inOrder.verify(getStdOutMock()).println("Gandalf enters the tower.");
inOrder.verify(getStdOutMock()).println("Dumbledore enters the tower.");
inOrder.verify(getStdOutMock()).println("Oz enters the tower.");
inOrder.verify(getStdOutMock()).println("Merlin is not allowed to enter!");
inOrder.verifyNoMoreInteractions();
assertTrue(appender.logContains("Gandalf enters the tower."));
assertTrue(appender.logContains("Dumbledore enters the tower."));
assertTrue(appender.logContains("Oz enters the tower."));
assertTrue(appender.logContains("Merlin is not allowed to enter!"));
assertEquals(4, appender.getLogSize());
}
}
}

View File

@ -22,17 +22,32 @@
*/
package com.iluwatar.proxy;
import com.iluwatar.proxy.utils.InMemoryAppender;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.mockito.InOrder;
import static org.mockito.Mockito.inOrder;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
/**
* Date: 12/28/15 - 9:18 PM
*
* @author Jeroen Meulemeester
*/
public class WizardTowerTest extends StdOutTest {
public class WizardTowerTest {
private InMemoryAppender appender;
@Before
public void setUp() {
appender = new InMemoryAppender(WizardTower.class);
}
@After
public void tearDown() {
appender.stop();
}
@Test
public void testEnter() throws Exception {
@ -48,13 +63,11 @@ public class WizardTowerTest extends StdOutTest {
tower.enter(wizard);
}
final InOrder inOrder = inOrder(getStdOutMock());
inOrder.verify(getStdOutMock()).println("Gandalf enters the tower.");
inOrder.verify(getStdOutMock()).println("Dumbledore enters the tower.");
inOrder.verify(getStdOutMock()).println("Oz enters the tower.");
inOrder.verify(getStdOutMock()).println("Merlin enters the tower.");
inOrder.verifyNoMoreInteractions();
assertTrue(appender.logContains("Gandalf enters the tower."));
assertTrue(appender.logContains("Dumbledore enters the tower."));
assertTrue(appender.logContains("Oz enters the tower."));
assertTrue(appender.logContains("Merlin enters the tower."));
assertEquals(4, appender.getLogSize());
}
}
}

View File

@ -0,0 +1,58 @@
/**
* The MIT License
* Copyright (c) 2014 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.proxy.utils;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.AppenderBase;
import org.slf4j.LoggerFactory;
import java.util.LinkedList;
import java.util.List;
public class InMemoryAppender extends AppenderBase<ILoggingEvent> {
private List<ILoggingEvent> log = new LinkedList<>();
public InMemoryAppender(Class clazz) {
((Logger) LoggerFactory.getLogger(clazz)).addAppender(this);
start();
}
public InMemoryAppender() {
((Logger) LoggerFactory.getLogger("root")).addAppender(this);
start();
}
@Override
protected void append(ILoggingEvent eventObject) {
log.add(eventObject);
}
public boolean logContains(String message) {
return log.stream().anyMatch(event -> event.getFormattedMessage().equals(message));
}
public int getLogSize() {
return log.size();
}
}

View File

@ -23,21 +23,35 @@
package com.iluwatar.reader.writer.lock;
import static org.mockito.Mockito.inOrder;
import com.iluwatar.reader.writer.lock.utils.InMemoryAppender;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import org.junit.Test;
import org.mockito.InOrder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.junit.Assert.assertTrue;
/**
* @author hongshuwei@gmail.com
*/
public class ReaderAndWriterTest extends StdOutTest {
public class ReaderAndWriterTest {
private InMemoryAppender appender;
@Before
public void setUp() {
appender = new InMemoryAppender();
}
@After
public void tearDown() {
appender.stop();
}
private static final Logger LOGGER = LoggerFactory.getLogger(ReaderAndWriterTest.class);
@ -65,11 +79,10 @@ public class ReaderAndWriterTest extends StdOutTest {
LOGGER.error("Error waiting for ExecutorService shutdown", e);
}
final InOrder inOrder = inOrder(getStdOutMock());
inOrder.verify(getStdOutMock()).println("Reader 1 begin");
inOrder.verify(getStdOutMock()).println("Reader 1 finish");
inOrder.verify(getStdOutMock()).println("Writer 1 begin");
inOrder.verify(getStdOutMock()).println("Writer 1 finish");
assertTrue(appender.logContains("Reader 1 begin"));
assertTrue(appender.logContains("Reader 1 finish"));
assertTrue(appender.logContains("Writer 1 begin"));
assertTrue(appender.logContains("Writer 1 finish"));
}
/**
@ -96,11 +109,10 @@ public class ReaderAndWriterTest extends StdOutTest {
LOGGER.error("Error waiting for ExecutorService shutdown", e);
}
final InOrder inOrder = inOrder(getStdOutMock());
inOrder.verify(getStdOutMock()).println("Writer 1 begin");
inOrder.verify(getStdOutMock()).println("Writer 1 finish");
inOrder.verify(getStdOutMock()).println("Reader 1 begin");
inOrder.verify(getStdOutMock()).println("Reader 1 finish");
assertTrue(appender.logContains("Writer 1 begin"));
assertTrue(appender.logContains("Writer 1 finish"));
assertTrue(appender.logContains("Reader 1 begin"));
assertTrue(appender.logContains("Reader 1 finish"));
}
}

View File

@ -22,22 +22,36 @@
*/
package com.iluwatar.reader.writer.lock;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.spy;
import com.iluwatar.reader.writer.lock.utils.InMemoryAppender;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import org.junit.Test;
import org.mockito.InOrder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static junit.framework.TestCase.assertTrue;
import static org.mockito.Mockito.spy;
/**
* @author hongshuwei@gmail.com
*/
public class ReaderTest extends StdOutTest {
public class ReaderTest {
private InMemoryAppender appender;
@Before
public void setUp() {
appender = new InMemoryAppender(Reader.class);
}
@After
public void tearDown() {
appender.stop();
}
private static final Logger LOGGER = LoggerFactory.getLogger(ReaderTest.class);
@ -66,11 +80,9 @@ public class ReaderTest extends StdOutTest {
// Read operation will hold the read lock 250 milliseconds, so here we prove that multiple reads
// can be performed in the same time.
final InOrder inOrder = inOrder(getStdOutMock());
inOrder.verify(getStdOutMock()).println("Reader 1 begin");
inOrder.verify(getStdOutMock()).println("Reader 2 begin");
inOrder.verify(getStdOutMock()).println("Reader 1 finish");
inOrder.verify(getStdOutMock()).println("Reader 2 finish");
assertTrue(appender.logContains("Reader 1 begin"));
assertTrue(appender.logContains("Reader 2 begin"));
assertTrue(appender.logContains("Reader 1 finish"));
assertTrue(appender.logContains("Reader 2 finish"));
}
}

View File

@ -1,76 +0,0 @@
/**
* The MIT License
* Copyright (c) 2014 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.reader.writer.lock;
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 some actions don't have any
* influence on 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

@ -22,22 +22,36 @@
*/
package com.iluwatar.reader.writer.lock;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.spy;
import com.iluwatar.reader.writer.lock.utils.InMemoryAppender;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import org.junit.Test;
import org.mockito.InOrder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.spy;
/**
* @author hongshuwei@gmail.com
*/
public class WriterTest extends StdOutTest {
public class WriterTest {
private InMemoryAppender appender;
@Before
public void setUp() {
appender = new InMemoryAppender(Writer.class);
}
@After
public void tearDown() {
appender.stop();
}
private static final Logger LOGGER = LoggerFactory.getLogger(WriterTest.class);
@ -67,10 +81,9 @@ public class WriterTest extends StdOutTest {
// Write operation will hold the write lock 250 milliseconds, so here we verify that when two
// writer execute concurrently, the second writer can only writes only when the first one is
// finished.
final InOrder inOrder = inOrder(getStdOutMock());
inOrder.verify(getStdOutMock()).println("Writer 1 begin");
inOrder.verify(getStdOutMock()).println("Writer 1 finish");
inOrder.verify(getStdOutMock()).println("Writer 2 begin");
inOrder.verify(getStdOutMock()).println("Writer 2 finish");
assertTrue(appender.logContains("Writer 1 begin"));
assertTrue(appender.logContains("Writer 1 finish"));
assertTrue(appender.logContains("Writer 2 begin"));
assertTrue(appender.logContains("Writer 2 finish"));
}
}

View File

@ -0,0 +1,54 @@
/**
* The MIT License
* Copyright (c) 2014 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.reader.writer.lock.utils;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.AppenderBase;
import org.slf4j.LoggerFactory;
import java.util.LinkedList;
import java.util.List;
public class InMemoryAppender extends AppenderBase<ILoggingEvent> {
private List<ILoggingEvent> log = new LinkedList<>();
public InMemoryAppender(Class clazz) {
((Logger) LoggerFactory.getLogger(clazz)).addAppender(this);
start();
}
public InMemoryAppender() {
((Logger) LoggerFactory.getLogger("root")).addAppender(this);
start();
}
@Override
protected void append(ILoggingEvent eventObject) {
log.add(eventObject);
}
public boolean logContains(String message) {
return log.stream().anyMatch(event -> event.getFormattedMessage().equals(message));
}
}

View File

@ -22,28 +22,64 @@
*/
package com.iluwatar.resource.acquisition.is.initialization;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.AppenderBase;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.mockito.InOrder;
import org.slf4j.LoggerFactory;
import static org.mockito.Mockito.inOrder;
import java.util.LinkedList;
import java.util.List;
import static org.junit.Assert.assertTrue;
/**
* Date: 12/28/15 - 9:31 PM
*
* @author Jeroen Meulemeester
*/
public class ClosableTest extends StdOutTest {
public class ClosableTest {
private InMemoryAppender appender;
@Before
public void setUp() {
appender = new InMemoryAppender();
}
@After
public void tearDown() {
appender.stop();
}
@Test
public void testOpenClose() throws Exception {
final InOrder inOrder = inOrder(getStdOutMock());
try (final SlidingDoor door = new SlidingDoor(); final TreasureChest chest = new TreasureChest()) {
inOrder.verify(getStdOutMock()).println("Sliding door opens.");
inOrder.verify(getStdOutMock()).println("Treasure chest opens.");
assertTrue(appender.logContains("Sliding door opens."));
assertTrue(appender.logContains("Treasure chest opens."));
}
inOrder.verify(getStdOutMock()).println("Treasure chest closes.");
inOrder.verify(getStdOutMock()).println("Sliding door closes.");
inOrder.verifyNoMoreInteractions();
assertTrue(appender.logContains("Treasure chest closes."));
assertTrue(appender.logContains("Sliding door closes."));
}
}
public class InMemoryAppender extends AppenderBase<ILoggingEvent> {
private List<ILoggingEvent> log = new LinkedList<>();
public InMemoryAppender() {
((Logger) LoggerFactory.getLogger("root")).addAppender(this);
start();
}
@Override
protected void append(ILoggingEvent eventObject) {
log.add(eventObject);
}
public boolean logContains(String message) {
return log.stream().anyMatch(event -> event.getMessage().equals(message));
}
}
}

View File

@ -1,75 +0,0 @@
/**
* The MIT License
* Copyright (c) 2014 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.resource.acquisition.is.initialization;
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 some actions don't have any
* influence on 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

@ -22,17 +22,19 @@
*/
package com.iluwatar.state;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.AppenderBase;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.mockito.InOrder;
import org.mockito.Mockito;
import org.slf4j.LoggerFactory;
import java.io.PrintStream;
import java.util.LinkedList;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.mockito.Mockito.mock;
/**
* Date: 12/29/15 - 8:27 PM
@ -41,31 +43,16 @@ import static org.mockito.Mockito.mock;
*/
public class MammothTest {
/**
* The mocked standard out {@link PrintStream}, required since some actions don't have any
* influence on accessible objects, except for writing to std-out using {@link System#out}
*/
private final PrintStream stdOutMock = mock(PrintStream.class);
private InMemoryAppender appender;
/**
* 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);
appender = new InMemoryAppender();
}
/**
* Removed the mocked std-out {@link PrintStream} again from the {@link System} class
*/
@After
public void tearDown() {
System.setOut(this.stdOutOrig);
appender.stop();
}
/**
@ -74,28 +61,27 @@ public class MammothTest {
*/
@Test
public void testTimePasses() {
final InOrder inOrder = Mockito.inOrder(this.stdOutMock);
final Mammoth mammoth = new Mammoth();
mammoth.observe();
inOrder.verify(this.stdOutMock).println("The mammoth is calm and peaceful.");
inOrder.verifyNoMoreInteractions();
assertEquals("The mammoth is calm and peaceful.", appender.getLastMessage());
assertEquals(1 , appender.getLogSize());
mammoth.timePasses();
inOrder.verify(this.stdOutMock).println("The mammoth gets angry!");
inOrder.verifyNoMoreInteractions();
assertEquals("The mammoth gets angry!", appender.getLastMessage());
assertEquals(2 , appender.getLogSize());
mammoth.observe();
inOrder.verify(this.stdOutMock).println("The mammoth is furious!");
inOrder.verifyNoMoreInteractions();
assertEquals("The mammoth is furious!", appender.getLastMessage());
assertEquals(3 , appender.getLogSize());
mammoth.timePasses();
inOrder.verify(this.stdOutMock).println("The mammoth calms down.");
inOrder.verifyNoMoreInteractions();
assertEquals("The mammoth calms down.", appender.getLastMessage());
assertEquals(4 , appender.getLogSize());
mammoth.observe();
inOrder.verify(this.stdOutMock).println("The mammoth is calm and peaceful.");
inOrder.verifyNoMoreInteractions();
assertEquals("The mammoth is calm and peaceful.", appender.getLastMessage());
assertEquals(5 , appender.getLogSize());
}
@ -109,4 +95,26 @@ public class MammothTest {
assertEquals("The mammoth", toString);
}
}
private class InMemoryAppender extends AppenderBase<ILoggingEvent> {
private List<ILoggingEvent> log = new LinkedList<>();
public InMemoryAppender() {
((Logger) LoggerFactory.getLogger("root")).addAppender(this);
start();
}
@Override
protected void append(ILoggingEvent eventObject) {
log.add(eventObject);
}
public int getLogSize() {
return log.size();
}
public String getLastMessage() {
return log.get(log.size() - 1).getFormattedMessage();
}
}
}

View File

@ -22,19 +22,22 @@
*/
package com.iluwatar.strategy;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.AppenderBase;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.slf4j.LoggerFactory;
import java.io.PrintStream;
import java.util.Arrays;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.junit.Assert.assertEquals;
/**
* Date: 12/29/15 - 10:58 PM
@ -71,20 +74,22 @@ public class DragonSlayingStrategyTest {
private final DragonSlayingStrategy strategy;
/**
* The expected action on the std-out
* The expected action in the log
*/
private final String expectedResult;
/**
* The mocked standard out {@link PrintStream}, required since some actions don't have any
* influence on accessible objects, except for writing to std-out using {@link System#out}
*/
private final PrintStream stdOutMock = mock(PrintStream.class);
private InMemoryAppender appender;
@Before
public void setUp() {
appender = new InMemoryAppender();
}
@After
public void tearDown() {
appender.stop();
}
/**
* Keep the original std-out so it can be restored after the test
*/
private final PrintStream stdOutOrig = System.out;
/**
* Create a new test instance for the given strategy
@ -97,30 +102,35 @@ public class DragonSlayingStrategyTest {
this.expectedResult = expectedResult;
}
/**
* 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);
}
/**
* Test if executing the strategy gives the correct response
*/
@Test
public void testExecute() {
this.strategy.execute();
verify(this.stdOutMock).println(this.expectedResult);
verifyNoMoreInteractions(this.stdOutMock);
assertEquals(this.expectedResult, appender.getLastMessage());
assertEquals(1, appender.getLogSize());
}
}
private class InMemoryAppender extends AppenderBase<ILoggingEvent> {
private List<ILoggingEvent> log = new LinkedList<>();
public InMemoryAppender() {
((Logger) LoggerFactory.getLogger("root")).addAppender(this);
start();
}
@Override
protected void append(ILoggingEvent eventObject) {
log.add(eventObject);
}
public int getLogSize() {
return log.size();
}
public String getLastMessage() {
return log.get(log.size() - 1).getFormattedMessage();
}
}
}

View File

@ -22,19 +22,19 @@
*/
package com.iluwatar.templatemethod;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.AppenderBase;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.mockito.InOrder;
import org.slf4j.LoggerFactory;
import java.io.PrintStream;
import java.util.LinkedList;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.verifyZeroInteractions;
import static org.junit.Assert.assertTrue;
/**
* Date: 12/30/15 - 18:12 PM
@ -43,6 +43,18 @@ import static org.mockito.Mockito.verifyZeroInteractions;
*/
public abstract class StealingMethodTest<M extends StealingMethod> {
private InMemoryAppender appender;
@Before
public void setUp() {
appender = new InMemoryAppender();
}
@After
public void tearDown() {
appender.stop();
}
/**
* The tested stealing method
*/
@ -68,17 +80,6 @@ public abstract class StealingMethodTest<M extends StealingMethod> {
*/
private final String expectedStealMethod;
/**
* The mocked standard out {@link PrintStream}, required since some actions don't have any
* influence on 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;
/**
* Create a new test for the given stealing method, together with the expected results
*
@ -98,22 +99,6 @@ public abstract class StealingMethodTest<M extends StealingMethod> {
this.expectedStealMethod = expectedStealMethod;
}
/**
* 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 thief picks the correct target
*/
@ -127,11 +112,11 @@ public abstract class StealingMethodTest<M extends StealingMethod> {
*/
@Test
public void testConfuseTarget() {
verifyZeroInteractions(this.stdOutMock);
assertEquals(0, appender.getLogSize());
this.method.confuseTarget(this.expectedTarget);
verify(this.stdOutMock).println(this.expectedConfuseMethod);
verifyNoMoreInteractions(this.stdOutMock);
assertEquals(this.expectedConfuseMethod, appender.getLastMessage());
assertEquals(1, appender.getLogSize());
}
/**
@ -139,11 +124,11 @@ public abstract class StealingMethodTest<M extends StealingMethod> {
*/
@Test
public void testStealTheItem() {
verifyZeroInteractions(this.stdOutMock);
assertEquals(0, appender.getLogSize());
this.method.stealTheItem(this.expectedTarget);
verify(this.stdOutMock).println(this.expectedStealMethod);
verifyNoMoreInteractions(this.stdOutMock);
assertEquals(this.expectedStealMethod, appender.getLastMessage());
assertEquals(1, appender.getLogSize());
}
/**
@ -151,14 +136,37 @@ public abstract class StealingMethodTest<M extends StealingMethod> {
*/
@Test
public void testSteal() {
final InOrder inOrder = inOrder(this.stdOutMock);
this.method.steal();
inOrder.verify(this.stdOutMock).println(this.expectedTargetResult);
inOrder.verify(this.stdOutMock).println(this.expectedConfuseMethod);
inOrder.verify(this.stdOutMock).println(this.expectedStealMethod);
inOrder.verifyNoMoreInteractions();
assertTrue(appender.logContains(this.expectedTargetResult));
assertTrue(appender.logContains(this.expectedConfuseMethod));
assertTrue(appender.logContains(this.expectedStealMethod));
assertEquals(3, appender.getLogSize());
}
}
private class InMemoryAppender extends AppenderBase<ILoggingEvent> {
private List<ILoggingEvent> log = new LinkedList<>();
public InMemoryAppender() {
((Logger) LoggerFactory.getLogger("root")).addAppender(this);
start();
}
@Override
protected void append(ILoggingEvent eventObject) {
log.add(eventObject);
}
public int getLogSize() {
return log.size();
}
public String getLastMessage() {
return log.get(log.size() - 1).getFormattedMessage();
}
public boolean logContains(String message) {
return log.stream().anyMatch(event -> event.getFormattedMessage().equals(message));
}
}
}

View File

@ -22,20 +22,40 @@
*/
package com.iluwatar.twin;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.AppenderBase;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.mockito.InOrder;
import org.slf4j.LoggerFactory;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import java.util.LinkedList;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.*;
/**
* Date: 12/30/15 - 18:44 PM
*
* @author Jeroen Meulemeester
*/
public class BallItemTest extends StdOutTest {
public class BallItemTest {
private InMemoryAppender appender;
@Before
public void setUp() {
appender = new InMemoryAppender();
}
@After
public void tearDown() {
appender.stop();
}
@Test
public void testClick() {
@ -63,10 +83,11 @@ public class BallItemTest extends StdOutTest {
ballItem.setTwin(ballThread);
ballItem.draw();
verify(getStdOutMock()).println("draw");
verify(getStdOutMock()).println("doDraw");
assertTrue(appender.logContains("draw"));
assertTrue(appender.logContains("doDraw"));
verifyNoMoreInteractions(ballThread, getStdOutMock());
verifyNoMoreInteractions(ballThread);
assertEquals(2, appender.getLogSize());
}
@Test
@ -76,9 +97,32 @@ public class BallItemTest extends StdOutTest {
ballItem.setTwin(ballThread);
ballItem.move();
verify(getStdOutMock()).println("move");
assertTrue(appender.logContains("move"));
verifyNoMoreInteractions(ballThread, getStdOutMock());
verifyNoMoreInteractions(ballThread);
assertEquals(1, appender.getLogSize());
}
}
public class InMemoryAppender extends AppenderBase<ILoggingEvent> {
private List<ILoggingEvent> log = new LinkedList<>();
public InMemoryAppender() {
((Logger) LoggerFactory.getLogger("root")).addAppender(this);
start();
}
@Override
protected void append(ILoggingEvent eventObject) {
log.add(eventObject);
}
public boolean logContains(String message) {
return log.stream().anyMatch(event -> event.getMessage().equals(message));
}
public int getLogSize() {
return log.size();
}
}
}

View File

@ -1,75 +0,0 @@
/**
* The MIT License
* Copyright (c) 2014 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.twin;
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 some actions don't have any
* influence on 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

@ -1,75 +0,0 @@
/**
* The MIT License
* Copyright (c) 2014 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.visitor;
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 some actions don't have any
* influence on 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

@ -22,19 +22,38 @@
*/
package com.iluwatar.visitor;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.AppenderBase;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.LoggerFactory;
import java.util.LinkedList;
import java.util.List;
import java.util.Optional;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.junit.Assert.assertEquals;
/**
* Date: 12/30/15 - 18:59 PM
*
* @author Jeroen Meulemeester
*/
public abstract class VisitorTest<V extends UnitVisitor> extends StdOutTest {
public abstract class VisitorTest<V extends UnitVisitor> {
private InMemoryAppender appender;
@Before
public void setUp() {
appender = new InMemoryAppender();
}
@After
public void tearDown() {
appender.stop();
}
/**
* The tested visitor instance
@ -76,27 +95,48 @@ public abstract class VisitorTest<V extends UnitVisitor> extends StdOutTest {
public void testVisitCommander() {
this.visitor.visitCommander(new Commander());
if (this.commanderResponse.isPresent()) {
verify(getStdOutMock()).println(this.commanderResponse.get());
assertEquals(this.commanderResponse.get(), appender.getLastMessage());
assertEquals(1, appender.getLogSize());
}
verifyNoMoreInteractions(getStdOutMock());
}
@Test
public void testVisitSergeant() {
this.visitor.visitSergeant(new Sergeant());
if (this.sergeantResponse.isPresent()) {
verify(getStdOutMock()).println(this.sergeantResponse.get());
assertEquals(this.sergeantResponse.get(), appender.getLastMessage());
assertEquals(1, appender.getLogSize());
}
verifyNoMoreInteractions(getStdOutMock());
}
@Test
public void testVisitSoldier() {
this.visitor.visitSoldier(new Soldier());
if (this.soldierResponse.isPresent()) {
verify(getStdOutMock()).println(this.soldierResponse.get());
assertEquals(this.soldierResponse.get(), appender.getLastMessage());
assertEquals(1, appender.getLogSize());
}
verifyNoMoreInteractions(getStdOutMock());
}
private class InMemoryAppender extends AppenderBase<ILoggingEvent> {
private List<ILoggingEvent> log = new LinkedList<>();
public InMemoryAppender() {
((Logger) LoggerFactory.getLogger("root")).addAppender(this);
start();
}
@Override
protected void append(ILoggingEvent eventObject) {
log.add(eventObject);
}
public int getLogSize() {
return log.size();
}
public String getLastMessage() {
return log.get(log.size() - 1).getFormattedMessage();
}
}
}