move design patterns to new module (#4206)

* move design patterns to new module

* fix logger import
This commit is contained in:
Loredana Crusoveanu
2018-05-11 10:11:13 +03:00
committed by Grzegorz Piwowarek
parent 4a08fd1352
commit 537c1d1150
137 changed files with 200 additions and 214 deletions
@@ -0,0 +1,30 @@
package com.baeldung;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import com.baeldung.adapter.AstonMartin;
import com.baeldung.adapter.BugattiVeyron;
import com.baeldung.adapter.McLaren;
import com.baeldung.adapter.Movable;
import com.baeldung.adapter.MovableAdapter;
import com.baeldung.adapter.MovableAdapterImpl;
public class AdapterPatternIntegrationTest {
@Test
public void givenMovableAdapter_WhenConvertingMPHToKMPH_thenSuccessfullyConverted() {
Movable bugattiVeyron = new BugattiVeyron();
MovableAdapter bugattiVeyronAdapter = new MovableAdapterImpl(bugattiVeyron);
assertEquals(bugattiVeyronAdapter.getSpeed(), 431.30312, 0.00001);
Movable mcLaren = new McLaren();
MovableAdapter mcLarenAdapter = new MovableAdapterImpl(mcLaren);
assertEquals(mcLarenAdapter.getSpeed(), 387.85094, 0.00001);
Movable astonMartin = new AstonMartin();
MovableAdapter astonMartinAdapter = new MovableAdapterImpl(astonMartin);
assertEquals(astonMartinAdapter.getSpeed(), 354.0548, 0.00001);
}
}
@@ -0,0 +1,26 @@
package com.baeldung;
import static org.junit.Assert.*;
import org.junit.Test;
import com.baeldung.bridge.Blue;
import com.baeldung.bridge.Red;
import com.baeldung.bridge.Shape;
import com.baeldung.bridge.Square;
import com.baeldung.bridge.Triangle;
public class BridgePatternIntegrationTest {
@Test
public void whenBridgePatternInvoked_thenConfigSuccess() {
//a square with red color
Shape square = new Square(new Red());
assertEquals(square.draw(), "Square drawn. Color is Red");
//a triangle with blue color
Shape triangle = new Triangle(new Blue());
assertEquals(triangle.draw(), "Triangle drawn. Color is Blue");
}
}
@@ -0,0 +1,25 @@
package com.baeldung;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import com.baeldung.decorator.BubbleLights;
import com.baeldung.decorator.ChristmasTree;
import com.baeldung.decorator.ChristmasTreeImpl;
import com.baeldung.decorator.Garland;
public class DecoratorPatternIntegrationTest {
@Test
public void givenDecoratorPattern_WhenDecoratorsInjectedAtRuntime_thenConfigSuccess() {
ChristmasTree tree1 = new Garland(new ChristmasTreeImpl());
assertEquals(tree1.decorate(),
"Christmas tree with Garland");
ChristmasTree tree2 = new BubbleLights(
new Garland(new Garland(new ChristmasTreeImpl())));
assertEquals(tree2.decorate(),
"Christmas tree with Garland with Garland with Bubble Lights");
}
}
@@ -0,0 +1,44 @@
package com.baeldung;
import static com.baeldung.util.LogerUtil.LOG;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import java.util.List;
import org.apache.log4j.spi.LoggingEvent;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.baeldung.proxy.ExpensiveObject;
import com.baeldung.proxy.ExpensiveObjectProxy;
public class ProxyPatternIntegrationTest {
public static TestAppenderDP appender;
@Before
public void setUp() {
appender = new TestAppenderDP();
LOG.addAppender(appender);
}
@Test
public void givenExpensiveObjectProxy_WhenObjectInitialized_thenInitializedOnlyOnce() {
ExpensiveObject object = new ExpensiveObjectProxy();
object.process();
object.process();
final List<LoggingEvent> log = appender.getLog();
assertThat((String) log.get(0).getMessage(), is("Loading initial configuration.."));
assertThat((String) log.get(1).getMessage(), is("processing complete."));
assertThat((String) log.get(2).getMessage(), is("processing complete."));
}
@After
public void tearDown() {
LOG.removeAppender(appender);
}
}
@@ -0,0 +1,29 @@
package com.baeldung;
import java.util.ArrayList;
import java.util.List;
import org.apache.log4j.AppenderSkeleton;
import org.apache.log4j.spi.LoggingEvent;
public class TestAppenderDP extends AppenderSkeleton {
private final List<LoggingEvent> log = new ArrayList<LoggingEvent>();
@Override
public boolean requiresLayout() {
return false;
}
@Override
protected void append(final LoggingEvent loggingEvent) {
log.add(loggingEvent);
}
@Override
public void close() {
}
public List<LoggingEvent> getLog() {
return new ArrayList<LoggingEvent>(log);
}
}
@@ -0,0 +1,37 @@
package com.baeldung.pattern.chainofresponsibility;
import org.junit.Test;
import static org.junit.Assert.assertTrue;
public class ChainOfResponsibilityTest {
private static AuthenticationProcessor getChainOfAuthProcessor() {
AuthenticationProcessor oAuthProcessor = new OAuthAuthenticationProcessor(null);
AuthenticationProcessor unamePasswordProcessor = new UsernamePasswordAuthenticationProcessor(oAuthProcessor);
return unamePasswordProcessor;
}
@Test
public void givenOAuthProvider_whenCheckingAuthorized_thenSuccess() {
AuthenticationProcessor authProcessorChain = getChainOfAuthProcessor();
boolean isAuthorized = authProcessorChain.isAuthorized(new OAuthTokenProvider());
assertTrue(isAuthorized);
}
@Test
public void givenUsernamePasswordProvider_whenCheckingAuthorized_thenSuccess() {
AuthenticationProcessor authProcessorChain = getChainOfAuthProcessor();
boolean isAuthorized = authProcessorChain.isAuthorized(new UsernamePasswordProvider());
assertTrue(isAuthorized);
}
@Test
public void givenSamlAuthProvider_whenCheckingAuthorized_thenFailure() {
AuthenticationProcessor authProcessorChain = getChainOfAuthProcessor();
boolean isAuthorized = authProcessorChain.isAuthorized(new SamlAuthenticationProvider());
assertTrue(!isAuthorized);
}
}
@@ -0,0 +1,16 @@
package com.baeldung.pattern.command.test;
import com.baeldung.pattern.command.command.OpenTextFileOperation;
import com.baeldung.pattern.command.command.TextFileOperation;
import com.baeldung.pattern.command.receiver.TextFile;
import org.junit.Test;
import static org.assertj.core.api.Assertions.*;
public class OpenTextFileOperationUnitTest {
@Test
public void givenOpenTextFileOperationIntance_whenCalledExecuteMethod_thenOneAssertion() {
TextFileOperation openTextFileOperation = new OpenTextFileOperation(new TextFile("file1.txt"));
assertThat(openTextFileOperation.execute()).isEqualTo("Opening file file1.txt");
}
}
@@ -0,0 +1,16 @@
package com.baeldung.pattern.command.test;
import com.baeldung.pattern.command.command.SaveTextFileOperation;
import com.baeldung.pattern.command.command.TextFileOperation;
import com.baeldung.pattern.command.receiver.TextFile;
import org.junit.Test;
import static org.assertj.core.api.Assertions.*;
public class SaveTextFileOperationUnitTest {
@Test
public void givenSaveTextFileOperationIntance_whenCalledExecuteMethod_thenOneAssertion() {
TextFileOperation openTextFileOperation = new SaveTextFileOperation(new TextFile("file1.txt"));
assertThat(openTextFileOperation.execute()).isEqualTo("Saving file file1.txt");
}
}
@@ -0,0 +1,68 @@
package com.baeldung.pattern.command.test;
import com.baeldung.pattern.command.command.OpenTextFileOperation;
import com.baeldung.pattern.command.command.SaveTextFileOperation;
import com.baeldung.pattern.command.command.TextFileOperation;
import com.baeldung.pattern.command.invoker.TextFileOperationExecutor;
import com.baeldung.pattern.command.receiver.TextFile;
import java.util.function.Function;
import org.junit.Test;
import static org.assertj.core.api.Assertions.*;
import org.junit.BeforeClass;
public class TextFileOperationExecutorUnitTest {
private static TextFileOperationExecutor textFileOperationExecutor;
@BeforeClass
public static void setUpTextFileOperationExecutor() {
textFileOperationExecutor = new TextFileOperationExecutor();
}
@Test
public void givenTextFileOPerationExecutorInstance_whenCalledexecuteOperationWithOpenTextOperation_thenOneAssertion() {
TextFileOperation textFileOperation = new OpenTextFileOperation(new TextFile("file1.txt"));
assertThat(textFileOperationExecutor.executeOperation(textFileOperation)).isEqualTo("Opening file file1.txt");
}
@Test
public void givenTextFileOPerationExecutorInstance_whenCalledexecuteOperationWithSaveTextOperation_thenOneAssertion() {
TextFileOperation textFileOperation = new SaveTextFileOperation(new TextFile("file1.txt"));
assertThat(textFileOperationExecutor.executeOperation(textFileOperation)).isEqualTo("Saving file file1.txt");
}
@Test
public void givenTextFileOperationExecutorInstance_whenCalledexecuteOperationWithTextFileOpenLambda_thenOneAssertion() {
assertThat(textFileOperationExecutor.executeOperation(() -> {return "Opening file file1.txt";})).isEqualTo("Opening file file1.txt");
}
@Test
public void givenTextFileOperationExecutorInstance_whenCalledexecuteOperationWithTextFileSaveLambda_thenOneAssertion() {
assertThat(textFileOperationExecutor.executeOperation(() -> {return "Saving file file1.txt";})).isEqualTo("Saving file file1.txt");
}
@Test
public void givenTextFileOperationExecutorInstance_whenCalledexecuteOperationWithTextFileOpenMethodReferenceOfExistingObject_thenOneAssertion() {
TextFile textFile = new TextFile("file1.txt");
assertThat(textFileOperationExecutor.executeOperation(textFile::open)).isEqualTo("Opening file file1.txt");
}
@Test
public void givenTextFileOperationExecutorInstance_whenCalledexecuteOperationWithTextFileSaveMethodReferenceOfExistingObject_thenOneAssertion() {
TextFile textFile = new TextFile("file1.txt");
assertThat(textFileOperationExecutor.executeOperation(textFile::save)).isEqualTo("Saving file file1.txt");
}
@Test
public void givenOpenTextFileOperationExecuteMethodReference_whenCalledApplyMethod_thenOneAssertion() {
Function<OpenTextFileOperation, String> executeMethodReference = OpenTextFileOperation::execute;
assertThat(executeMethodReference.apply(new OpenTextFileOperation(new TextFile("file1.txt")))).isEqualTo("Opening file file1.txt");
}
@Test
public void givenSaveTextFileOperationExecuteMethodReference_whenCalledApplyMethod_thenOneAssertion() {
Function<SaveTextFileOperation, String> executeMethodReference = SaveTextFileOperation::execute;
assertThat(executeMethodReference.apply(new SaveTextFileOperation(new TextFile("file1.txt")))).isEqualTo("Saving file file1.txt");
}
}
@@ -0,0 +1,42 @@
package com.baeldung.pattern.command.test;
import com.baeldung.pattern.command.receiver.TextFile;
import org.junit.Test;
import static org.assertj.core.api.Assertions.*;
import org.junit.BeforeClass;
public class TextFileUnitTest {
private static TextFile textFile;
@BeforeClass
public static void setUpTextFileInstance() {
textFile = new TextFile("file1.txt");
}
@Test
public void givenTextFileInstance_whenCalledopenMethod_thenOneAssertion() {
assertThat(textFile.open()).isEqualTo("Opening file file1.txt");
}
@Test
public void givenTextFileInstance_whenCalledwriteMethod_thenOneAssertion() {
assertThat(textFile.write()).isEqualTo("Writing to file file1.txt");
}
@Test
public void givenTextFileInstance_whenCalledsaveMethod_thenOneAssertion() {
assertThat(textFile.save()).isEqualTo("Saving file file1.txt");
}
@Test
public void givenTextFileInstance_whenCalledcopyMethod_thenOneAssertion() {
assertThat(textFile.copy()).isEqualTo("Copying file file1.txt");
}
@Test
public void givenTextFileInstance_whenCalledpasteMethod_thenOneAssertion() {
assertThat(textFile.paste()).isEqualTo("Pasting file file1.txt");
}
}
@@ -0,0 +1,23 @@
package com.baeldung.creational.abstractfactory;
import static org.junit.Assert.*;
import org.junit.Test;
public class AbstractPatternIntegrationTest {
@Test
public void givenAbstractFactory_whenGettingObjects_thenSuccessful() {
AbstractFactory abstractFactory;
//creating a brown toy dog
abstractFactory = FactoryProvider.getFactory("Toy");
Animal toy = abstractFactory.getAnimal("Dog");
abstractFactory = FactoryProvider.getFactory("Color");
Color color = abstractFactory.getColor("Brown");
String result = "A " + toy.getType() + " with " + color.getColor() + " color " + toy.makeSound();
assertEquals("A Dog with brown color Barks", result);
}
}
@@ -0,0 +1,33 @@
package com.baeldung.creational.builder;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
public class BuilderPatternIntegrationTest {
@Test
public void whenCreatingObjectThroughBuilder_thenObjectValid() {
BankAccount newAccount = new BankAccount
.BankAccountBuilder("Jon", "22738022275")
.withEmail("jon@example.com")
.wantNewsletter(true)
.build();
assertEquals(newAccount.getName(), "Jon");
assertEquals(newAccount.getAccountNumber(), "22738022275");
assertEquals(newAccount.getEmail(), "jon@example.com");
assertEquals(newAccount.isNewsletter(), true);
}
@Test
public void whenSkippingOptionalParameters_thenObjectValid() {
BankAccount newAccount = new BankAccount
.BankAccountBuilder("Jon", "22738022275")
.build();
assertEquals(newAccount.getName(), "Jon");
assertEquals(newAccount.getAccountNumber(), "22738022275");
assertEquals(newAccount.getEmail(), null);
assertEquals(newAccount.isNewsletter(), false);
}
}
@@ -0,0 +1,32 @@
package com.baeldung.creational.factory;
import static org.junit.Assert.*;
import org.junit.Test;
public class FactoryIntegrationTest {
@Test
public void whenUsingFactoryForSquare_thenCorrectObjectReturned() {
Polygon p;
PolygonFactory factory = new PolygonFactory();
//get the shape which has 4 sides
p = factory.getPolygon(4);
String result = "The shape with 4 sides is a " + p.getType();
assertEquals("The shape with 4 sides is a Square", result);
}
@Test
public void whenUsingFactoryForOctagon_thenCorrectObjectReturned() {
Polygon p;
PolygonFactory factory = new PolygonFactory();
//get the shape which has 4 sides
p = factory.getPolygon(8);
String result = "The shape with 8 sides is a " + p.getType();
assertEquals("The shape with 8 sides is a Octagon", result);
}
}
@@ -0,0 +1,26 @@
package com.baeldung.creational.singleton;
import org.junit.Test;
import static org.junit.Assert.*;
public class SingletonIntegrationTest {
@Test
/**
* Although there is absolutely no way to determine whether
* a class is Singleton, in this test case, we will just
* check for two objects if they point to same instance or
* not. We will also check for their hashcode.
*/
public void whenGettingMultipleObjects_thenAllPointToSame() {
//first object
Singleton obj1 = Singleton.getInstance();
//Second object
Singleton obj2 = Singleton.getInstance();
assertTrue(obj1 == obj2);
assertEquals(obj1.hashCode(), obj2.hashCode());
}
}
@@ -0,0 +1,85 @@
package com.baeldung.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.util.ArrayList;
import java.util.List;
import static org.junit.Assert.*;
public class CarEngineFacadeTest {
private InMemoryCustomTestAppender appender;
@Before
public void setUp() {
appender = new InMemoryCustomTestAppender();
}
@After
public void tearDown() {
appender.stop();
}
@Test
public void whenStartEngine_thenAllNecessaryActionsPerformed() {
CarEngineFacade carEngineFacade = new CarEngineFacade();
carEngineFacade.startEngine();
assertTrue(appender.logContains("Fuel injector ready to inject fuel."));
assertTrue(appender.logContains("Getting air measurements.."));
assertTrue(appender.logContains("Air provided!"));
assertTrue(appender.logContains("Fuel injector ready to inject fuel."));
assertTrue(appender.logContains("Fuel Pump is pumping fuel.."));
assertTrue(appender.logContains("Fuel injected."));
assertTrue(appender.logContains("Starting.."));
assertTrue(appender.logContains("Setting temperature upper limit to 90"));
assertTrue(appender.logContains("Cooling Controller ready!"));
assertTrue(appender.logContains("Setting radiator speed to 10"));
assertTrue(appender.logContains("Catalytic Converter switched on!"));
}
@Test
public void whenStopEngine_thenAllNecessaryActionsPerformed() {
CarEngineFacade carEngineFacade = new CarEngineFacade();
carEngineFacade.stopEngine();
assertTrue(appender.logContains("Stopping Fuel injector.."));
assertTrue(appender.logContains("Catalytic Converter switched off!"));
assertTrue(appender.logContains("Scheduled cooling with maximum allowed temperature 50"));
assertTrue(appender.logContains("Getting temperature from the sensor.."));
assertTrue(appender.logContains("Radiator switched on!"));
assertTrue(appender.logContains("Stopping Cooling Controller.."));
assertTrue(appender.logContains("Radiator switched off!"));
assertTrue(appender.logContains("Air controller switched off."));
}
private class InMemoryCustomTestAppender extends AppenderBase<ILoggingEvent> {
private List<ILoggingEvent> logs = new ArrayList<>();
public InMemoryCustomTestAppender() {
((Logger) LoggerFactory.getLogger("root")).addAppender(this);
start();
}
@Override
protected void append(ILoggingEvent eventObject) {
logs.add(eventObject);
}
public boolean logContains(String message) {
return logs.stream().anyMatch(event -> event.getFormattedMessage().equals(message));
}
}
}
@@ -0,0 +1,42 @@
package com.baeldung.flyweight;
import java.awt.Color;
import org.junit.Assert;
import org.junit.Test;
/**
* Unit test for {@link VehicleFactory}.
*
* @author Donato Rimenti
*/
public class FlyweightUnitTest {
/**
* Checks that when the {@link VehicleFactory} is asked to provide two
* vehicles of different colors, the objects returned are different.
*/
@Test
public void givenDifferentFlyweightObjects_whenEquals_thenFalse() {
Vehicle blackVehicle = VehicleFactory.createVehicle(Color.BLACK);
Vehicle blueVehicle = VehicleFactory.createVehicle(Color.BLUE);
Assert.assertNotNull("Object returned by the factory is null!", blackVehicle);
Assert.assertNotNull("Object returned by the factory is null!", blueVehicle);
Assert.assertNotEquals("Objects returned by the factory are equals!", blackVehicle, blueVehicle);
}
/**
* Checks that when the {@link VehicleFactory} is asked to provide two
* vehicles of the same colors, the same object is returned twice.
*/
@Test
public void givenSameFlyweightObjects_whenEquals_thenTrue() {
Vehicle blackVehicle = VehicleFactory.createVehicle(Color.BLACK);
Vehicle anotherBlackVehicle = VehicleFactory.createVehicle(Color.BLACK);
Assert.assertNotNull("Object returned by the factory is null!", blackVehicle);
Assert.assertNotNull("Object returned by the factory is null!", anotherBlackVehicle);
Assert.assertEquals("Objects returned by the factory are not equals!", blackVehicle, anotherBlackVehicle);
}
}
@@ -0,0 +1,47 @@
package com.baeldung.observer;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import com.baeldung.observer.NewsAgency;
import com.baeldung.observer.NewsChannel;
public class ObserverIntegrationTest {
@Test
public void whenChangingNewsAgencyState_thenNewsChannelNotified() {
NewsAgency observable = new NewsAgency();
NewsChannel observer = new NewsChannel();
observable.addObserver(observer);
observable.setNews("news");
assertEquals(observer.getNews(), "news");
}
@Test
public void whenChangingONewsAgencyState_thenONewsChannelNotified() {
ONewsAgency observable = new ONewsAgency();
ONewsChannel observer = new ONewsChannel();
observable.addObserver(observer);
observable.setNews("news");
assertEquals(observer.getNews(), "news");
}
@Test
public void whenChangingPCLNewsAgencyState_thenONewsChannelNotified() {
PCLNewsAgency observable = new PCLNewsAgency();
PCLNewsChannel observer = new PCLNewsChannel();
observable.addPropertyChangeListener(observer);
observable.setNews("news");
assertEquals(observer.getNews(), "news");
}
}
@@ -0,0 +1,119 @@
package com.baeldung.singleton.synchronization;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.junit.Assert;
import org.junit.Test;
/**
* Unit tests for the singleton synchronization package with the same name.
*
* @author Donato Rimenti
*
*/
public class SingletonSynchronizationUnitTest {
/**
* Size of the thread pools used.
*/
private static final int POOL_SIZE = 1_000;
/**
* Number of tasks to submit.
*/
private static final int TASKS_TO_SUBMIT = 1_000_000;
/**
* Tests the thread-safety of {@link DraconianSingleton}.
*/
@Test
public void givenDraconianSingleton_whenMultithreadInstancesEquals_thenTrue() {
ExecutorService executor = Executors.newFixedThreadPool(POOL_SIZE);
Set<DraconianSingleton> resultSet = Collections.synchronizedSet(new HashSet<DraconianSingleton>());
// Submits the instantiation tasks.
for (int i = 0; i < TASKS_TO_SUBMIT; i++) {
executor.submit(() -> resultSet.add(DraconianSingleton.getInstance()));
}
// Since the instance of the object we inserted into the set is always
// the same, the size should be one.
Assert.assertEquals(1, resultSet.size());
}
/**
* Tests the thread-safety of {@link DclSingleton}.
*/
@Test
public void givenDclSingleton_whenMultithreadInstancesEquals_thenTrue() {
ExecutorService executor = Executors.newFixedThreadPool(POOL_SIZE);
Set<DclSingleton> resultSet = Collections.synchronizedSet(new HashSet<DclSingleton>());
// Submits the instantiation tasks.
for (int i = 0; i < TASKS_TO_SUBMIT; i++) {
executor.submit(() -> resultSet.add(DclSingleton.getInstance()));
}
// Since the instance of the object we inserted into the set is always
// the same, the size should be one.
Assert.assertEquals(1, resultSet.size());
}
/**
* Tests the thread-safety of {@link EarlyInitSingleton}.
*/
@Test
public void givenEarlyInitSingleton_whenMultithreadInstancesEquals_thenTrue() {
ExecutorService executor = Executors.newFixedThreadPool(POOL_SIZE);
Set<EarlyInitSingleton> resultSet = Collections.synchronizedSet(new HashSet<EarlyInitSingleton>());
// Submits the instantiation tasks.
for (int i = 0; i < TASKS_TO_SUBMIT; i++) {
executor.submit(() -> resultSet.add(EarlyInitSingleton.getInstance()));
}
// Since the instance of the object we inserted into the set is always
// the same, the size should be one.
Assert.assertEquals(1, resultSet.size());
}
/**
* Tests the thread-safety of {@link InitOnDemandSingleton}.
*/
@Test
public void givenInitOnDemandSingleton_whenMultithreadInstancesEquals_thenTrue() {
ExecutorService executor = Executors.newFixedThreadPool(POOL_SIZE);
Set<InitOnDemandSingleton> resultSet = Collections.synchronizedSet(new HashSet<InitOnDemandSingleton>());
// Submits the instantiation tasks.
for (int i = 0; i < TASKS_TO_SUBMIT; i++) {
executor.submit(() -> resultSet.add(InitOnDemandSingleton.getInstance()));
}
// Since the instance of the object we inserted into the set is always
// the same, the size should be one.
Assert.assertEquals(1, resultSet.size());
}
/**
* Tests the thread-safety of {@link EnumSingleton}.
*/
@Test
public void givenEnumSingleton_whenMultithreadInstancesEquals_thenTrue() {
ExecutorService executor = Executors.newFixedThreadPool(POOL_SIZE);
Set<EnumSingleton> resultSet = Collections.synchronizedSet(new HashSet<EnumSingleton>());
// Submits the instantiation tasks.
for (int i = 0; i < TASKS_TO_SUBMIT; i++) {
executor.submit(() -> resultSet.add(EnumSingleton.INSTANCE));
}
// Since the instance of the object we inserted into the set is always
// the same, the size should be one.
Assert.assertEquals(1, resultSet.size());
}
}
@@ -0,0 +1,87 @@
package com.baeldung.pattern.templatemethod.test;
import com.baeldung.pattern.templatemethod.model.Computer;
import com.baeldung.pattern.templatemethod.model.HighEndComputerBuilder;
import com.baeldung.pattern.templatemethod.model.StandardComputerBuilder;
import org.junit.Assert;
import static org.junit.Assert.assertEquals;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.junit.Assert.assertThat;
public class TemplateMethodPatternTest {
private static StandardComputerBuilder standardComputerBuilder;
private static HighEndComputerBuilder highEndComputerBuilder;
@BeforeClass
public static void setUpStandardComputerBuilderInstance() {
standardComputerBuilder = new StandardComputerBuilder();
}
@BeforeClass
public static void setUpHighEndComputerBuilderInstance() {
highEndComputerBuilder = new HighEndComputerBuilder();
}
@Test
public void givenStandardMotherBoard_whenAddingMotherBoard_thenEqualAssertion() {
standardComputerBuilder.addMotherboard();
assertEquals("Standard Motherboard", standardComputerBuilder.getComputerParts().get("Motherboard"));
}
@Test
public void givenStandardMotherboard_whenSetup_thenTwoEqualAssertions() {
standardComputerBuilder.setupMotherboard();
assertEquals("Screwing the standard motherboard to the case.", standardComputerBuilder.getMotherboardSetupStatus().get(0));
assertEquals("Pluging in the power supply connectors.", standardComputerBuilder.getMotherboardSetupStatus().get(1));
}
@Test
public void givenStandardProcessor_whenAddingProcessor_thenEqualAssertion() {
standardComputerBuilder.addProcessor();
assertEquals("Standard Processor", standardComputerBuilder.getComputerParts().get("Processor"));
}
@Test
public void givenAllStandardParts_whenBuildingComputer_thenTwoParts() {
standardComputerBuilder.buildComputer();
assertEquals(2, standardComputerBuilder.getComputerParts().size());
}
@Test
public void givenAllStandardParts_whenComputerisBuilt_thenComputerInstance() {
assertThat(standardComputerBuilder.buildComputer(), instanceOf(Computer.class));
}
@Test
public void givenHighEnddMotherBoard_whenAddingMotherBoard_thenEqualAssertion() {
highEndComputerBuilder.addMotherboard();
Assert.assertEquals("High-end Motherboard", highEndComputerBuilder.getComputerParts().get("Motherboard"));
}
@Test
public void givenHighEnddMotheroboard_whenSetup_thenTwoEqualAssertions() {
highEndComputerBuilder.setupMotherboard();
assertEquals("Screwing the high-end motherboard to the case.", highEndComputerBuilder.getMotherboardSetupStatus().get(0));
assertEquals("Pluging in the power supply connectors.", highEndComputerBuilder.getMotherboardSetupStatus().get(1));
}
@Test
public void givenHightEndProcessor_whenAddingProcessor_thenEqualAssertion() {
highEndComputerBuilder.addProcessor();
assertEquals("High-end Processor", highEndComputerBuilder.getComputerParts().get("Processor"));
}
@Test
public void givenAllHighEnddParts_whenBuildingComputer_thenTwoParts() {
highEndComputerBuilder.buildComputer();
assertEquals(2, highEndComputerBuilder.getComputerParts().size());
}
@Test
public void givenAllHighEndParts_whenComputerisBuilt_thenComputerInstance() {
assertThat(standardComputerBuilder.buildComputer(), instanceOf(Computer.class));
}
}