Compare commits

..

2 Commits

119 changed files with 528 additions and 326 deletions

View File

@ -32,7 +32,6 @@ import java.util.stream.Stream;
import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
/** /**
* AbstractDocument test class * AbstractDocument test class
@ -82,8 +81,8 @@ public class AbstractDocumentTest {
Map<String, Object> props = new HashMap<>(); Map<String, Object> props = new HashMap<>();
props.put(KEY, VALUE); props.put(KEY, VALUE);
DocumentImplementation document = new DocumentImplementation(props); DocumentImplementation document = new DocumentImplementation(props);
assertTrue(document.toString().contains(KEY)); assertNotNull(document.toString().contains(KEY));
assertTrue(document.toString().contains(VALUE)); assertNotNull(document.toString().contains(VALUE));
} }
} }

View File

@ -25,19 +25,27 @@ package com.iluwatar.acyclicvisitor;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.groups.Tuple.tuple; import static org.assertj.core.groups.Tuple.tuple;
import static uk.org.lidalia.slf4jext.Level.INFO; import static uk.org.lidalia.slf4jext.Level.INFO;
import static org.mockito.Mockito.mock;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import uk.org.lidalia.slf4jtest.TestLogger; import uk.org.lidalia.slf4jtest.TestLogger;
import uk.org.lidalia.slf4jtest.TestLoggerFactory; import uk.org.lidalia.slf4jtest.TestLoggerFactory;
import org.junit.jupiter.api.Test;
import com.iluwatar.acyclicvisitor.ConfigureForUnixVisitor;
import com.iluwatar.acyclicvisitor.Hayes;
import com.iluwatar.acyclicvisitor.HayesVisitor;
import com.iluwatar.acyclicvisitor.Zoom;
import com.iluwatar.acyclicvisitor.ZoomVisitor;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
/** /**
* ConfigureForUnixVisitor test class * ConfigureForUnixVisitor test class
*/ */
public class ConfigureForUnixVisitorTest { public class ConfigureForUnixVisitorTest {
private static final TestLogger LOGGER = TestLoggerFactory.getTestLogger(ConfigureForUnixVisitor.class); TestLogger logger = TestLoggerFactory.getTestLogger(ConfigureForUnixVisitor.class);
@AfterEach @AfterEach
public void clearLoggers() { public void clearLoggers() {
@ -51,7 +59,7 @@ public class ConfigureForUnixVisitorTest {
conUnix.visit(zoom); conUnix.visit(zoom);
assertThat(LOGGER.getLoggingEvents()).extracting("level", "message").contains( assertThat(logger.getLoggingEvents()).extracting("level", "message").contains(
tuple(INFO, zoom + " used with Unix configurator.")); tuple(INFO, zoom + " used with Unix configurator."));
} }
} }

View File

@ -31,7 +31,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
*/ */
public class InventoryControllerTest { public class InventoryControllerTest {
@Test @Test
public void testGetProductInventories() { public void testGetProductInventories() throws Exception {
InventoryController inventoryController = new InventoryController(); InventoryController inventoryController = new InventoryController();
int numberOfInventories = inventoryController.getProductInventories(); int numberOfInventories = inventoryController.getProductInventories();

View File

@ -22,6 +22,7 @@
*/ */
package com.iluwatar.ambassador; package com.iluwatar.ambassador;
import com.iluwatar.ambassador.util.RandomProvider;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -31,9 +32,10 @@ import static java.lang.Thread.sleep;
* A remote legacy application represented by a Singleton implementation. * A remote legacy application represented by a Singleton implementation.
*/ */
public class RemoteService implements RemoteServiceInterface { public class RemoteService implements RemoteServiceInterface {
static final int THRESHOLD = 200;
private static final Logger LOGGER = LoggerFactory.getLogger(RemoteService.class); private static final Logger LOGGER = LoggerFactory.getLogger(RemoteService.class);
private static RemoteService service = null; private static RemoteService service = null;
private final RandomProvider randomProvider;
static synchronized RemoteService getRemoteService() { static synchronized RemoteService getRemoteService() {
if (service == null) { if (service == null) {
@ -42,24 +44,33 @@ public class RemoteService implements RemoteServiceInterface {
return service; return service;
} }
private RemoteService() {} private RemoteService() {
this(Math::random);
}
/**
* This constuctor is used for testing purposes only.
*/
RemoteService(RandomProvider randomProvider) {
this.randomProvider = randomProvider;
}
/** /**
* Remote function takes a value and multiplies it by 10 taking a random amount of time. * Remote function takes a value and multiplies it by 10 taking a random amount of time.
* Will sometimes return -1. This imitates connectivity issues a client might have to account for. * Will sometimes return -1. This imitates connectivity issues a client might have to account for.
* @param value integer value to be multiplied. * @param value integer value to be multiplied.
* @return if waitTime is more than 200ms, it returns value * 10, otherwise -1. * @return if waitTime is less than {@link RemoteService#THRESHOLD}, it returns value * 10,
* otherwise {@link RemoteServiceInterface#FAILURE}.
*/ */
@Override @Override
public long doRemoteFunction(int value) { public long doRemoteFunction(int value) {
long waitTime = (long) Math.floor(Math.random() * 1000); long waitTime = (long) Math.floor(randomProvider.random() * 1000);
try { try {
sleep(waitTime); sleep(waitTime);
} catch (InterruptedException e) { } catch (InterruptedException e) {
LOGGER.error("Thread sleep state interrupted", e); LOGGER.error("Thread sleep state interrupted", e);
} }
return waitTime >= 200 ? value * 10 : -1; return waitTime <= THRESHOLD ? value * 10 : FAILURE;
} }
} }

View File

@ -26,6 +26,7 @@ package com.iluwatar.ambassador;
* Interface shared by ({@link RemoteService}) and ({@link ServiceAmbassador}). * Interface shared by ({@link RemoteService}) and ({@link ServiceAmbassador}).
*/ */
interface RemoteServiceInterface { interface RemoteServiceInterface {
int FAILURE = -1;
long doRemoteFunction(int value) throws Exception; long doRemoteFunction(int value) throws Exception;
} }

View File

@ -59,15 +59,15 @@ public class ServiceAmbassador implements RemoteServiceInterface {
private long safeCall(int value) { private long safeCall(int value) {
int retries = 0; int retries = 0;
long result = -1; long result = FAILURE;
for (int i = 0; i < RETRIES; i++) { for (int i = 0; i < RETRIES; i++) {
if (retries >= RETRIES) { if (retries >= RETRIES) {
return -1; return FAILURE;
} }
if ((result = checkLatency(value)) == -1) { if ((result = checkLatency(value)) == FAILURE) {
LOGGER.info("Failed to reach remote: (" + (i + 1) + ")"); LOGGER.info("Failed to reach remote: (" + (i + 1) + ")");
retries++; retries++;
try { try {

View File

@ -0,0 +1,8 @@
package com.iluwatar.ambassador.util;
/**
* An interface for randomness. Useful for testing purposes.
*/
public interface RandomProvider {
double random();
}

View File

@ -24,6 +24,8 @@ package com.iluwatar.ambassador;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertTrue;
/** /**
* Test for {@link Client} * Test for {@link Client}
*/ */
@ -35,6 +37,6 @@ public class ClientTest {
Client client = new Client(); Client client = new Client();
long result = client.useService(10); long result = client.useService(10);
assert result == 100 || result == -1; assertTrue(result == 100 || result == RemoteService.FAILURE);
} }
} }

View File

@ -22,16 +22,43 @@
*/ */
package com.iluwatar.ambassador; package com.iluwatar.ambassador;
import com.iluwatar.ambassador.util.RandomProvider;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
/** /**
* Test for {@link RemoteService} * Test for {@link RemoteService}
*/ */
public class RemoteServiceTest { public class RemoteServiceTest {
@Test @Test
public void test() { public void testFailedCall() {
long result = RemoteService.getRemoteService().doRemoteFunction(10); RemoteService remoteService = new RemoteService(
assert result == 100 || result == -1; new StaticRandomProvider(0.21));
long result = remoteService.doRemoteFunction(10);
assertEquals(RemoteServiceInterface.FAILURE, result);
}
@Test
public void testSuccessfulCall() {
RemoteService remoteService = new RemoteService(
new StaticRandomProvider(0.2));
long result = remoteService.doRemoteFunction(10);
assertEquals(100, result);
}
private class StaticRandomProvider implements RandomProvider {
private double value;
StaticRandomProvider(double value) {
this.value = value;
}
@Override
public double random() {
return value;
}
} }
} }

View File

@ -24,6 +24,8 @@ package com.iluwatar.ambassador;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertTrue;
/** /**
* Test for {@link ServiceAmbassador} * Test for {@link ServiceAmbassador}
*/ */
@ -32,6 +34,6 @@ public class ServiceAmbassadorTest {
@Test @Test
public void test() { public void test() {
long result = new ServiceAmbassador().doRemoteFunction(10); long result = new ServiceAmbassador().doRemoteFunction(10);
assert result == 100 || result == -1; assertTrue(result == 100 || result == RemoteServiceInterface.FAILURE);
} }
} }

View File

@ -37,7 +37,7 @@ public class HammerTest extends WeaponTest {
* underlying weapon implementation. * underlying weapon implementation.
*/ */
@Test @Test
public void testHammer() { public void testHammer() throws Exception {
final Hammer hammer = spy(new Hammer(mock(FlyingEnchantment.class))); final Hammer hammer = spy(new Hammer(mock(FlyingEnchantment.class)));
testBasicWeaponActions(hammer); testBasicWeaponActions(hammer);
} }

View File

@ -37,7 +37,7 @@ public class SwordTest extends WeaponTest {
* underlying weapon implementation. * underlying weapon implementation.
*/ */
@Test @Test
public void testSword() { public void testSword() throws Exception {
final Sword sword = spy(new Sword(mock(FlyingEnchantment.class))); final Sword sword = spy(new Sword(mock(FlyingEnchantment.class)));
testBasicWeaponActions(sword); testBasicWeaponActions(sword);
} }

View File

@ -41,7 +41,12 @@ public class App {
*/ */
public static void main(String[] args) { public static void main(String[] args) {
Task task = new SimpleTask(); Task task = new SimpleTask();
Callback callback = () -> LOGGER.info("I'm done now."); Callback callback = new Callback() {
@Override
public void call() {
LOGGER.info("I'm done now.");
}
};
task.executeWith(callback); task.executeWith(callback);
} }
} }

View File

@ -38,6 +38,29 @@ public class CallbackTest {
@Test @Test
public void test() { public void test() {
Callback callback = new Callback() {
@Override
public void call() {
callingCount++;
}
};
Task task = new SimpleTask();
assertEquals(new Integer(0), callingCount, "Initial calling count of 0");
task.executeWith(callback);
assertEquals(new Integer(1), callingCount, "Callback called once");
task.executeWith(callback);
assertEquals(new Integer(2), callingCount, "Callback called twice");
}
@Test
public void testWithLambdasExample() {
Callback callback = () -> callingCount++; Callback callback = () -> callingCount++;
Task task = new SimpleTask(); Task task = new SimpleTask();

View File

@ -43,7 +43,7 @@ public class OrcKingTest {
}; };
@Test @Test
public void testMakeRequest() { public void testMakeRequest() throws Exception {
final OrcKing king = new OrcKing(); final OrcKing king = new OrcKing();
for (final Request request : REQUESTS) { for (final Request request : REQUESTS) {

View File

@ -26,10 +26,10 @@ package com.iluwatar.collectionpipeline;
* A Car class that has the properties of make, model, year and category. * A Car class that has the properties of make, model, year and category.
*/ */
public class Car { public class Car {
private final String make; private String make;
private final String model; private String model;
private final int year; private int year;
private final Category category; private Category category;
/** /**
* Constructor to create an instance of car. * Constructor to create an instance of car.

View File

@ -71,7 +71,7 @@ public class ConverterTest {
user.getFirstName().toLowerCase() + user.getLastName().toLowerCase() + "@whatever.com")); user.getFirstName().toLowerCase() + user.getLastName().toLowerCase() + "@whatever.com"));
User u1 = new User("John", "Doe", false, "12324"); User u1 = new User("John", "Doe", false, "12324");
UserDto userDto = converter.convertFromEntity(u1); UserDto userDto = converter.convertFromEntity(u1);
assertEquals("johndoe@whatever.com", userDto.getEmail()); assertEquals(userDto.getEmail(), "johndoe@whatever.com");
} }
/** /**
@ -83,6 +83,6 @@ public class ConverterTest {
ArrayList<User> users = Lists.newArrayList(new User("Camile", "Tough", false, "124sad"), ArrayList<User> users = Lists.newArrayList(new User("Camile", "Tough", false, "124sad"),
new User("Marti", "Luther", true, "42309fd"), new User("Kate", "Smith", true, "if0243")); new User("Marti", "Luther", true, "42309fd"), new User("Kate", "Smith", true, "if0243"));
List<User> fromDtos = userConverter.createFromDtos(userConverter.createFromEntities(users)); List<User> fromDtos = userConverter.createFromDtos(userConverter.createFromEntities(users));
assertEquals(users, fromDtos); assertEquals(fromDtos, users);
} }
} }

View File

@ -96,7 +96,7 @@ public class IntegrationTest {
@Test @Test
public void testGetAuthorBooks() { public void testGetAuthorBooks() {
List<Book> books = queryService.getAuthorBooks("username1"); List<Book> books = queryService.getAuthorBooks("username1");
assertEquals(2, books.size()); assertTrue(books.size() == 2);
assertTrue(books.contains(new Book("title1", 10))); assertTrue(books.contains(new Book("title1", 10)));
assertTrue(books.contains(new Book("new_title2", 30))); assertTrue(books.contains(new Book("new_title2", 30)));
} }

View File

@ -88,7 +88,13 @@ public class CustomerTest {
@Test @Test
public void testToString() { public void testToString() {
assertEquals(String.format("Customer{id=%s, firstName='%s', lastName='%s'}", final StringBuffer buffer = new StringBuffer();
customer.getId(), customer.getFirstName(), customer.getLastName()), customer.toString()); buffer.append("Customer{id=")
.append("" + customer.getId())
.append(", firstName='")
.append(customer.getFirstName())
.append("\', lastName='")
.append(customer.getLastName() + "\'}");
assertEquals(buffer.toString(), customer.toString());
} }
} }

View File

@ -257,7 +257,7 @@ public class DbCustomerDaoTest {
private void assertCustomerCountIs(int count) throws Exception { private void assertCustomerCountIs(int count) throws Exception {
try (Stream<Customer> allCustomers = dao.getAll()) { try (Stream<Customer> allCustomers = dao.getAll()) {
assertEquals(count, allCustomers.count()); assertTrue(allCustomers.count() == count);
} }
} }

View File

@ -156,7 +156,7 @@ public class InMemoryCustomerDaoTest {
private void assertCustomerCountIs(int count) throws Exception { private void assertCustomerCountIs(int count) throws Exception {
try (Stream<Customer> allCustomers = dao.getAll()) { try (Stream<Customer> allCustomers = dao.getAll()) {
assertEquals(count, allCustomers.count()); assertTrue(allCustomers.count() == count);
} }
} }
} }

View File

@ -21,7 +21,6 @@ package com.iluwatar.datamapper;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
/** /**
* The Data Mapper (DM) is a layer of software that separates the in-memory objects from the * The Data Mapper (DM) is a layer of software that separates the in-memory objects from the
@ -44,29 +43,27 @@ public class DataMapperTest {
final StudentDataMapper mapper = new StudentDataMapperImpl(); final StudentDataMapper mapper = new StudentDataMapperImpl();
/* Create new student */ /* Create new student */
int studentId = 1; Student student = new Student(1, "Adam", 'A');
Student student = new Student(studentId, "Adam", 'A');
/* Add student in respectibe db */ /* Add student in respectibe db */
mapper.insert(student); mapper.insert(student);
/* Check if student is added in db */ /* Check if student is added in db */
assertEquals(studentId, mapper.find(student.getStudentId()).get().getStudentId()); assertEquals(student.getStudentId(), mapper.find(student.getStudentId()).get().getStudentId());
/* Update existing student object */ /* Update existing student object */
String updatedName = "AdamUpdated"; student = new Student(student.getStudentId(), "AdamUpdated", 'A');
student = new Student(student.getStudentId(), updatedName, 'A');
/* Update student in respectibe db */ /* Update student in respectibe db */
mapper.update(student); mapper.update(student);
/* Check if student is updated in db */ /* Check if student is updated in db */
assertEquals(updatedName, mapper.find(student.getStudentId()).get().getName()); assertEquals(mapper.find(student.getStudentId()).get().getName(), "AdamUpdated");
/* Delete student in db */ /* Delete student in db */
mapper.delete(student); mapper.delete(student);
/* Result should be false */ /* Result should be false */
assertFalse(mapper.find(student.getStudentId()).isPresent()); assertEquals(false, mapper.find(student.getStudentId()).isPresent());
} }
} }

View File

@ -20,9 +20,7 @@ package com.iluwatar.datamapper;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.assertTrue;
/** /**
@ -30,27 +28,28 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
*/ */
public final class StudentTest { public final class StudentTest {
@Test
/** /**
* This API tests the equality behaviour of Student object * This API tests the equality behaviour of Student object
* Object Equality should work as per logic defined in equals method * Object Equality should work as per logic defined in equals method
* *
* @throws Exception if any execution error during test * @throws Exception if any execution error during test
*/ */
@Test
public void testEquality() throws Exception { public void testEquality() throws Exception {
/* Create some students */ /* Create some students */
final Student firstStudent = new Student(1, "Adam", 'A'); final Student firstStudent = new Student(1, "Adam", 'A');
final Student secondStudent = new Student(2, "Donald", 'B'); final Student secondStudent = new Student(2, "Donald", 'B');
final Student secondSameStudent = new Student(2, "Donald", 'B'); final Student secondSameStudent = new Student(2, "Donald", 'B');
final Student firstSameStudent = firstStudent;
/* Check equals functionality: should return 'true' */ /* Check equals functionality: should return 'true' */
assertEquals(firstStudent, firstStudent); assertTrue(firstStudent.equals(firstSameStudent));
/* Check equals functionality: should return 'false' */ /* Check equals functionality: should return 'false' */
assertNotEquals(firstStudent, secondStudent); assertFalse(firstStudent.equals(secondStudent));
/* Check equals functionality: should return 'true' */ /* Check equals functionality: should return 'true' */
assertEquals(secondStudent, secondSameStudent); assertTrue(secondStudent.equals(secondSameStudent));
} }
} }

View File

@ -30,7 +30,6 @@ import java.util.ArrayList;
import java.util.List; import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
/** /**
* tests {@link CustomerResource}. * tests {@link CustomerResource}.
@ -46,10 +45,10 @@ public class CustomerResourceTest {
List<CustomerDto> allCustomers = customerResource.getAllCustomers(); List<CustomerDto> allCustomers = customerResource.getAllCustomers();
assertEquals(1, allCustomers.size()); assertEquals(allCustomers.size(), 1);
assertEquals("1", allCustomers.get(0).getId()); assertEquals(allCustomers.get(0).getId(), "1");
assertEquals("Melody", allCustomers.get(0).getFirstName()); assertEquals(allCustomers.get(0).getFirstName(), "Melody");
assertEquals("Yates", allCustomers.get(0).getLastName()); assertEquals(allCustomers.get(0).getLastName(), "Yates");
} }
@Test @Test
@ -60,9 +59,9 @@ public class CustomerResourceTest {
customerResource.save(customer); customerResource.save(customer);
List<CustomerDto> allCustomers = customerResource.getAllCustomers(); List<CustomerDto> allCustomers = customerResource.getAllCustomers();
assertEquals("1", allCustomers.get(0).getId()); assertEquals(allCustomers.get(0).getId(), "1");
assertEquals("Rita", allCustomers.get(0).getFirstName()); assertEquals(allCustomers.get(0).getFirstName(), "Rita");
assertEquals("Reynolds", allCustomers.get(0).getLastName()); assertEquals(allCustomers.get(0).getLastName(), "Reynolds");
} }
@Test @Test
@ -76,7 +75,7 @@ public class CustomerResourceTest {
customerResource.delete(customer.getId()); customerResource.delete(customer.getId());
List<CustomerDto> allCustomers = customerResource.getAllCustomers(); List<CustomerDto> allCustomers = customerResource.getAllCustomers();
assertTrue(allCustomers.isEmpty()); assertEquals(allCustomers.size(), 0);
} }
} }

View File

@ -40,7 +40,7 @@ import com.iluwatar.delegation.simple.printers.HpPrinter;
*/ */
public class App { public class App {
private static final String MESSAGE_TO_PRINT = "hello world"; public static final String MESSAGE_TO_PRINT = "hello world";
/** /**
* Program entry point * Program entry point

View File

@ -22,7 +22,6 @@
*/ */
package org.dirty.flag; package org.dirty.flag;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.List; import java.util.List;
@ -42,7 +41,7 @@ public class DirtyFlagTest {
public void testIsDirty() { public void testIsDirty() {
DataFetcher df = new DataFetcher(); DataFetcher df = new DataFetcher();
List<String> countries = df.fetch(); List<String> countries = df.fetch();
assertFalse(countries.isEmpty()); assertTrue(!countries.isEmpty());
} }
@Test @Test

View File

@ -51,7 +51,7 @@ public class AggregatorRoute extends RouteBuilder {
* @throws Exception in case of exception during configuration * @throws Exception in case of exception during configuration
*/ */
@Override @Override
public void configure() { public void configure() throws Exception {
// Main route // Main route
from("{{entry}}").aggregate(constant(true), aggregator) from("{{entry}}").aggregate(constant(true), aggregator)
.completionSize(3).completionInterval(2000) .completionSize(3).completionInterval(2000)

View File

@ -70,7 +70,7 @@ public class App {
}); });
context.start(); context.start();
context.getRoutes().forEach(r -> LOGGER.info(r.toString())); context.getRoutes().stream().forEach(r -> LOGGER.info(r.toString()));
context.stop(); context.stop();
} }
} }

View File

@ -65,7 +65,7 @@ public class App {
}); });
ProducerTemplate template = context.createProducerTemplate(); ProducerTemplate template = context.createProducerTemplate();
context.start(); context.start();
context.getRoutes().forEach(r -> LOGGER.info(r.toString())); context.getRoutes().stream().forEach(r -> LOGGER.info(r.toString()));
template.sendBody("direct:origin", "Hello from origin"); template.sendBody("direct:origin", "Hello from origin");
context.stop(); context.stop();
} }

View File

@ -76,7 +76,7 @@ public class KingJoffreyTest {
private class InMemoryAppender extends AppenderBase<ILoggingEvent> { private class InMemoryAppender extends AppenderBase<ILoggingEvent> {
private List<ILoggingEvent> log = new LinkedList<>(); private List<ILoggingEvent> log = new LinkedList<>();
public InMemoryAppender(Class<?> clazz) { public InMemoryAppender(Class clazz) {
((Logger) LoggerFactory.getLogger(clazz)).addAppender(this); ((Logger) LoggerFactory.getLogger(clazz)).addAppender(this);
start(); start();
} }

View File

@ -35,7 +35,7 @@ import static org.junit.jupiter.api.Assertions.assertNotNull;
public class WeekdayTest { public class WeekdayTest {
@Test @Test
public void testToString() { public void testToString() throws Exception {
for (final Weekday weekday : Weekday.values()) { for (final Weekday weekday : Weekday.values()) {
final String toString = weekday.toString(); final String toString = weekday.toString();
assertNotNull(toString); assertNotNull(toString);

View File

@ -16,12 +16,11 @@
*/ */
package com.iluwatar.event.asynchronous; package com.iluwatar.event.asynchronous;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.assertTrue;
@ -31,19 +30,26 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
* *
*/ */
public class EventAsynchronousTest { public class EventAsynchronousTest {
App app;
private static final Logger LOGGER = LoggerFactory.getLogger(EventAsynchronousTest.class); private static final Logger LOGGER = LoggerFactory.getLogger(EventAsynchronousTest.class);
@BeforeEach
public void setUp() {
app = new App();
}
@Test @Test
public void testAsynchronousEvent() { public void testAsynchronousEvent() {
EventManager eventManager = new EventManager(); EventManager eventManager = new EventManager();
try { try {
int aEventId = eventManager.createAsync(60); int aEventId = eventManager.createAsync(60);
eventManager.start(aEventId); eventManager.start(aEventId);
assertEquals(1, eventManager.getEventPool().size()); assertTrue(eventManager.getEventPool().size() == 1);
assertTrue(eventManager.getEventPool().size() < EventManager.MAX_RUNNING_EVENTS); assertTrue(eventManager.getEventPool().size() < EventManager.MAX_RUNNING_EVENTS);
assertEquals(-1, eventManager.numOfCurrentlyRunningSyncEvent()); assertTrue(eventManager.numOfCurrentlyRunningSyncEvent() == -1);
eventManager.cancel(aEventId); eventManager.cancel(aEventId);
assertTrue(eventManager.getEventPool().isEmpty()); assertTrue(eventManager.getEventPool().size() == 0);
} catch (MaxNumOfEventsAllowedException | LongRunningEventException | EventDoesNotExistException e) { } catch (MaxNumOfEventsAllowedException | LongRunningEventException | EventDoesNotExistException e) {
LOGGER.error(e.getMessage()); LOGGER.error(e.getMessage());
} }
@ -55,11 +61,11 @@ public class EventAsynchronousTest {
try { try {
int sEventId = eventManager.create(60); int sEventId = eventManager.create(60);
eventManager.start(sEventId); eventManager.start(sEventId);
assertEquals(1, eventManager.getEventPool().size()); assertTrue(eventManager.getEventPool().size() == 1);
assertTrue(eventManager.getEventPool().size() < EventManager.MAX_RUNNING_EVENTS); assertTrue(eventManager.getEventPool().size() < EventManager.MAX_RUNNING_EVENTS);
assertNotEquals(-1, eventManager.numOfCurrentlyRunningSyncEvent()); assertTrue(eventManager.numOfCurrentlyRunningSyncEvent() != -1);
eventManager.cancel(sEventId); eventManager.cancel(sEventId);
assertTrue(eventManager.getEventPool().isEmpty()); assertTrue(eventManager.getEventPool().size() == 0);
} catch (MaxNumOfEventsAllowedException | LongRunningEventException | EventDoesNotExistException } catch (MaxNumOfEventsAllowedException | LongRunningEventException | EventDoesNotExistException
| InvalidOperationException e) { | InvalidOperationException e) {
LOGGER.error(e.getMessage()); LOGGER.error(e.getMessage());
@ -67,7 +73,7 @@ public class EventAsynchronousTest {
} }
@Test @Test
public void testUnsuccessfulSynchronousEvent() { public void testUnsuccessfulSynchronousEvent() throws InvalidOperationException {
assertThrows(InvalidOperationException.class, () -> { assertThrows(InvalidOperationException.class, () -> {
EventManager eventManager = new EventManager(); EventManager eventManager = new EventManager();
try { try {
@ -88,7 +94,7 @@ public class EventAsynchronousTest {
int eventTime = 1; int eventTime = 1;
int sEventId = eventManager.create(eventTime); int sEventId = eventManager.create(eventTime);
assertEquals(1, eventManager.getEventPool().size()); assertTrue(eventManager.getEventPool().size() == 1);
eventManager.start(sEventId); eventManager.start(sEventId);
long currentTime = System.currentTimeMillis(); long currentTime = System.currentTimeMillis();
@ -98,7 +104,7 @@ public class EventAsynchronousTest {
while (System.currentTimeMillis() < endTime) { while (System.currentTimeMillis() < endTime) {
} }
assertTrue(eventManager.getEventPool().isEmpty()); assertTrue(eventManager.getEventPool().size() == 0);
} catch (MaxNumOfEventsAllowedException | LongRunningEventException | EventDoesNotExistException } catch (MaxNumOfEventsAllowedException | LongRunningEventException | EventDoesNotExistException
| InvalidOperationException e) { | InvalidOperationException e) {
@ -115,7 +121,7 @@ public class EventAsynchronousTest {
int aEventId1 = eventManager.createAsync(eventTime); int aEventId1 = eventManager.createAsync(eventTime);
int aEventId2 = eventManager.createAsync(eventTime); int aEventId2 = eventManager.createAsync(eventTime);
int aEventId3 = eventManager.createAsync(eventTime); int aEventId3 = eventManager.createAsync(eventTime);
assertEquals(3, eventManager.getEventPool().size()); assertTrue(eventManager.getEventPool().size() == 3);
eventManager.start(aEventId1); eventManager.start(aEventId1);
eventManager.start(aEventId2); eventManager.start(aEventId2);
@ -127,7 +133,7 @@ public class EventAsynchronousTest {
while (System.currentTimeMillis() < endTime) { while (System.currentTimeMillis() < endTime) {
} }
assertTrue(eventManager.getEventPool().isEmpty()); assertTrue(eventManager.getEventPool().size() == 0);
} catch (MaxNumOfEventsAllowedException | LongRunningEventException | EventDoesNotExistException e) { } catch (MaxNumOfEventsAllowedException | LongRunningEventException | EventDoesNotExistException e) {
LOGGER.error(e.getMessage()); LOGGER.error(e.getMessage());

View File

@ -74,7 +74,7 @@ public class App {
LOGGER.info("Running the system first time............"); LOGGER.info("Running the system first time............");
eventProcessor.reset(); eventProcessor.reset();
LOGGER.info("Creating the accounts............"); LOGGER.info("Creating th accounts............");
eventProcessor.process(new AccountCreateEvent( eventProcessor.process(new AccountCreateEvent(
0, new Date().getTime(), ACCOUNT_OF_DAENERYS, "Daenerys Targaryen")); 0, new Date().getTime(), ACCOUNT_OF_DAENERYS, "Daenerys Targaryen"));
@ -98,7 +98,7 @@ public class App {
LOGGER.info(AccountAggregate.getAccount(ACCOUNT_OF_DAENERYS).toString()); LOGGER.info(AccountAggregate.getAccount(ACCOUNT_OF_DAENERYS).toString());
LOGGER.info(AccountAggregate.getAccount(ACCOUNT_OF_JON).toString()); LOGGER.info(AccountAggregate.getAccount(ACCOUNT_OF_JON).toString());
LOGGER.info("At that point system had a shut down, state in memory is cleared............"); LOGGER.info("At that point system had a shot down, state in memory is cleared............");
AccountAggregate.resetState(); AccountAggregate.resetState();
LOGGER.info("Recover the system by the events in journal file............"); LOGGER.info("Recover the system by the events in journal file............");

View File

@ -92,7 +92,7 @@ public class MoneyTransferEvent extends DomainEvent {
} }
Account accountTo = AccountAggregate.getAccount(accountNoTo); Account accountTo = AccountAggregate.getAccount(accountNoTo);
if (accountTo == null) { if (accountTo == null) {
throw new RuntimeException("Account not found " + accountNoTo); throw new RuntimeException("Account not found" + accountTo);
} }
accountFrom.handleTransferFromEvent(this); accountFrom.handleTransferFromEvent(this);

View File

@ -44,17 +44,26 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
@EnableRuleMigrationSupport @EnableRuleMigrationSupport
public class SimpleFileWriterTest { public class SimpleFileWriterTest {
/**
* Create a temporary folder, used to generate files in during this test
*/
@Rule @Rule
public final TemporaryFolder testFolder = new TemporaryFolder(); public final TemporaryFolder testFolder = new TemporaryFolder();
/**
* Verify if the given writer is not 'null'
*/
@Test @Test
public void testWriterNotNull() throws Exception { public void testWriterNotNull() throws Exception {
final File temporaryFile = this.testFolder.newFile(); final File temporaryFile = this.testFolder.newFile();
new SimpleFileWriter(temporaryFile.getPath(), Assertions::assertNotNull); new SimpleFileWriter(temporaryFile.getPath(), Assertions::assertNotNull);
} }
/**
* Test if the {@link SimpleFileWriter} creates a file if it doesn't exist
*/
@Test @Test
public void testCreatesNonExistentFile() throws Exception { public void testNonExistentFile() throws Exception {
final File nonExistingFile = new File(this.testFolder.getRoot(), "non-existing-file"); final File nonExistingFile = new File(this.testFolder.getRoot(), "non-existing-file");
assertFalse(nonExistingFile.exists()); assertFalse(nonExistingFile.exists());
@ -62,8 +71,11 @@ public class SimpleFileWriterTest {
assertTrue(nonExistingFile.exists()); assertTrue(nonExistingFile.exists());
} }
/**
* Test if the data written to the file writer actually gets in the file
*/
@Test @Test
public void testContentsAreWrittenToFile() throws Exception { public void testActualWrite() throws Exception {
final String testMessage = "Test message"; final String testMessage = "Test message";
final File temporaryFile = this.testFolder.newFile(); final File temporaryFile = this.testFolder.newFile();
@ -73,15 +85,17 @@ public class SimpleFileWriterTest {
assertTrue(Files.lines(temporaryFile.toPath()).allMatch(testMessage::equals)); assertTrue(Files.lines(temporaryFile.toPath()).allMatch(testMessage::equals));
} }
/**
* Verify if an {@link IOException} during the write ripples through
*/
@Test @Test
public void testRipplesIoExceptionOccurredWhileWriting() { public void testIoException() throws Exception {
String message = "Some error";
assertThrows(IOException.class, () -> { assertThrows(IOException.class, () -> {
final File temporaryFile = this.testFolder.newFile(); final File temporaryFile = this.testFolder.newFile();
new SimpleFileWriter(temporaryFile.getPath(), writer -> { new SimpleFileWriter(temporaryFile.getPath(), writer -> {
throw new IOException(message); throw new IOException("");
});
}); });
}, message);
} }
} }

View File

@ -32,16 +32,16 @@ import units.CommanderUnit;
*/ */
public class Commander implements CommanderExtension { public class Commander implements CommanderExtension {
private static final Logger LOGGER = LoggerFactory.getLogger(Commander.class);
private CommanderUnit unit; private CommanderUnit unit;
public Commander(CommanderUnit commanderUnit) { public Commander(CommanderUnit commanderUnit) {
this.unit = commanderUnit; this.unit = commanderUnit;
} }
final Logger logger = LoggerFactory.getLogger(Commander.class);
@Override @Override
public void commanderReady() { public void commanderReady() {
LOGGER.info("[Commander] " + unit.getName() + " is ready!"); logger.info("[Commander] " + unit.getName() + " is ready!");
} }
} }

View File

@ -32,16 +32,16 @@ import units.SergeantUnit;
*/ */
public class Sergeant implements SergeantExtension { public class Sergeant implements SergeantExtension {
private static final Logger LOGGER = LoggerFactory.getLogger(Sergeant.class);
private SergeantUnit unit; private SergeantUnit unit;
public Sergeant(SergeantUnit sergeantUnit) { public Sergeant(SergeantUnit sergeantUnit) {
this.unit = sergeantUnit; this.unit = sergeantUnit;
} }
final Logger logger = LoggerFactory.getLogger(Sergeant.class);
@Override @Override
public void sergeantReady() { public void sergeantReady() {
LOGGER.info("[Sergeant] " + unit.getName() + " is ready! "); logger.info("[Sergeant] " + unit.getName() + " is ready! ");
} }
} }

View File

@ -31,7 +31,6 @@ import units.SoldierUnit;
* Class defining Soldier * Class defining Soldier
*/ */
public class Soldier implements SoldierExtension { public class Soldier implements SoldierExtension {
private static final Logger LOGGER = LoggerFactory.getLogger(Soldier.class);
private SoldierUnit unit; private SoldierUnit unit;
@ -39,8 +38,10 @@ public class Soldier implements SoldierExtension {
this.unit = soldierUnit; this.unit = soldierUnit;
} }
final Logger logger = LoggerFactory.getLogger(Soldier.class);
@Override @Override
public void soldierReady() { public void soldierReady() {
LOGGER.info("[Solider] " + unit.getName() + " is ready!"); logger.info("[Solider] " + unit.getName() + " is ready!");
} }
} }

View File

@ -30,7 +30,7 @@ import units.CommanderUnit;
*/ */
public class CommanderTest { public class CommanderTest {
@Test @Test
public void commanderReady() { public void commanderReady() throws Exception {
final Commander commander = new Commander(new CommanderUnit("CommanderUnitTest")); final Commander commander = new Commander(new CommanderUnit("CommanderUnitTest"));
commander.commanderReady(); commander.commanderReady();

View File

@ -33,13 +33,13 @@ import static org.junit.jupiter.api.Assertions.assertNull;
*/ */
public class CommanderUnitTest { public class CommanderUnitTest {
@Test @Test
public void getUnitExtension() { public void getUnitExtension() throws Exception {
final Unit unit = new CommanderUnit("CommanderUnitName"); final Unit unit = new CommanderUnit("CommanderUnitName");
assertNull(unit.getUnitExtension("SoldierExtension")); assertNull(unit.getUnitExtension("SoldierExtension"));
assertNull(unit.getUnitExtension("SergeantExtension")); assertNull(unit.getUnitExtension("SergeantExtension"));
assertNotNull(unit.getUnitExtension("CommanderExtension")); assertNotNull((CommanderExtension) unit.getUnitExtension("CommanderExtension"));
} }
} }

View File

@ -33,12 +33,12 @@ import static org.junit.jupiter.api.Assertions.assertNull;
*/ */
public class SergeantUnitTest { public class SergeantUnitTest {
@Test @Test
public void getUnitExtension() { public void getUnitExtension() throws Exception {
final Unit unit = new SergeantUnit("SergeantUnitName"); final Unit unit = new SergeantUnit("SergeantUnitName");
assertNull(unit.getUnitExtension("SoldierExtension")); assertNull(unit.getUnitExtension("SoldierExtension"));
assertNotNull(unit.getUnitExtension("SergeantExtension")); assertNotNull((SergeantExtension) unit.getUnitExtension("SergeantExtension"));
assertNull(unit.getUnitExtension("CommanderExtension")); assertNull(unit.getUnitExtension("CommanderExtension"));
} }

View File

@ -33,11 +33,11 @@ import static org.junit.jupiter.api.Assertions.assertNull;
*/ */
public class SoldierUnitTest { public class SoldierUnitTest {
@Test @Test
public void getUnitExtension() { public void getUnitExtension() throws Exception {
final Unit unit = new SoldierUnit("SoldierUnitName"); final Unit unit = new SoldierUnit("SoldierUnitName");
assertNotNull(unit.getUnitExtension("SoldierExtension")); assertNotNull((SoldierExtension) unit.getUnitExtension("SoldierExtension"));
assertNull(unit.getUnitExtension("SergeantExtension")); assertNull(unit.getUnitExtension("SergeantExtension"));
assertNull(unit.getUnitExtension("CommanderExtension")); assertNull(unit.getUnitExtension("CommanderExtension"));

View File

@ -83,7 +83,7 @@ public class FactoryKitTest {
* @param weapon weapon object which is to be verified * @param weapon weapon object which is to be verified
* @param clazz expected class of the weapon * @param clazz expected class of the weapon
*/ */
private void verifyWeapon(Weapon weapon, Class<?> clazz) { private void verifyWeapon(Weapon weapon, Class clazz) {
assertTrue(clazz.isInstance(weapon), "Weapon must be an object of: " + clazz.getName()); assertTrue(clazz.isInstance(weapon), "Weapon must be an object of: " + clazz.getName());
} }
} }

View File

@ -40,14 +40,14 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
public class PropertiesFeatureToggleVersionTest { public class PropertiesFeatureToggleVersionTest {
@Test @Test
public void testNullPropertiesPassed() { public void testNullPropertiesPassed() throws Exception {
assertThrows(IllegalArgumentException.class, () -> { assertThrows(IllegalArgumentException.class, () -> {
new PropertiesFeatureToggleVersion(null); new PropertiesFeatureToggleVersion(null);
}); });
} }
@Test @Test
public void testNonBooleanProperty() { public void testNonBooleanProperty() throws Exception {
assertThrows(IllegalArgumentException.class, () -> { assertThrows(IllegalArgumentException.class, () -> {
final Properties properties = new Properties(); final Properties properties = new Properties();
properties.setProperty("enhancedWelcome", "Something"); properties.setProperty("enhancedWelcome", "Something");
@ -56,7 +56,7 @@ public class PropertiesFeatureToggleVersionTest {
} }
@Test @Test
public void testFeatureTurnedOn() { public void testFeatureTurnedOn() throws Exception {
final Properties properties = new Properties(); final Properties properties = new Properties();
properties.put("enhancedWelcome", true); properties.put("enhancedWelcome", true);
Service service = new PropertiesFeatureToggleVersion(properties); Service service = new PropertiesFeatureToggleVersion(properties);
@ -66,7 +66,7 @@ public class PropertiesFeatureToggleVersionTest {
} }
@Test @Test
public void testFeatureTurnedOff() { public void testFeatureTurnedOff() throws Exception {
final Properties properties = new Properties(); final Properties properties = new Properties();
properties.put("enhancedWelcome", false); properties.put("enhancedWelcome", false);
Service service = new PropertiesFeatureToggleVersion(properties); Service service = new PropertiesFeatureToggleVersion(properties);

View File

@ -41,27 +41,27 @@ public class TieredFeatureToggleVersionTest {
final Service service = new TieredFeatureToggleVersion(); final Service service = new TieredFeatureToggleVersion();
@BeforeEach @BeforeEach
public void setUp() { public void setUp() throws Exception {
UserGroup.addUserToPaidGroup(paidUser); UserGroup.addUserToPaidGroup(paidUser);
UserGroup.addUserToFreeGroup(freeUser); UserGroup.addUserToFreeGroup(freeUser);
} }
@Test @Test
public void testGetWelcomeMessageForPaidUser() { public void testGetWelcomeMessageForPaidUser() throws Exception {
final String welcomeMessage = service.getWelcomeMessage(paidUser); final String welcomeMessage = service.getWelcomeMessage(paidUser);
final String expected = "You're amazing Jamie Coder. Thanks for paying for this awesome software."; final String expected = "You're amazing Jamie Coder. Thanks for paying for this awesome software.";
assertEquals(expected, welcomeMessage); assertEquals(expected, welcomeMessage);
} }
@Test @Test
public void testGetWelcomeMessageForFreeUser() { public void testGetWelcomeMessageForFreeUser() throws Exception {
final String welcomeMessage = service.getWelcomeMessage(freeUser); final String welcomeMessage = service.getWelcomeMessage(freeUser);
final String expected = "I suppose you can use this software."; final String expected = "I suppose you can use this software.";
assertEquals(expected, welcomeMessage); assertEquals(expected, welcomeMessage);
} }
@Test @Test
public void testIsEnhancedAlwaysTrueAsTiered() { public void testIsEnhancedAlwaysTrueAsTiered() throws Exception {
assertTrue(service.isEnhanced()); assertTrue(service.isEnhanced());
} }
} }

View File

@ -171,11 +171,11 @@ public class SimpleFluentIterable<E> implements FluentIterable<E> {
/** /**
* @return a FluentIterable from a given iterable. Calls the SimpleFluentIterable constructor. * @return a FluentIterable from a given iterable. Calls the SimpleFluentIterable constructor.
*/ */
public static <E> FluentIterable<E> from(Iterable<E> iterable) { public static final <E> FluentIterable<E> from(Iterable<E> iterable) {
return new SimpleFluentIterable<>(iterable); return new SimpleFluentIterable<>(iterable);
} }
public static <E> FluentIterable<E> fromCopyOf(Iterable<E> iterable) { public static final <E> FluentIterable<E> fromCopyOf(Iterable<E> iterable) {
List<E> copy = FluentIterable.copyToList(iterable); List<E> copy = FluentIterable.copyToList(iterable);
return new SimpleFluentIterable<>(copy); return new SimpleFluentIterable<>(copy);
} }

View File

@ -179,15 +179,15 @@ public abstract class FluentIterableTest {
} }
@Test @Test
public void testForEach() { public void testForEach() throws Exception {
final List<Integer> integers = Arrays.asList(1, 2, 3); final List<Integer> integers = Arrays.asList(1, 2, 3);
final Consumer<Integer> consumer = mock(Consumer.class); final Consumer<Integer> consumer = mock(Consumer.class);
createFluentIterable(integers).forEach(consumer); createFluentIterable(integers).forEach(consumer);
verify(consumer, times(1)).accept(1); verify(consumer, times(1)).accept(Integer.valueOf(1));
verify(consumer, times(1)).accept(2); verify(consumer, times(1)).accept(Integer.valueOf(2));
verify(consumer, times(1)).accept(3); verify(consumer, times(1)).accept(Integer.valueOf(3));
verifyNoMoreInteractions(consumer); verifyNoMoreInteractions(consumer);
} }

View File

@ -36,7 +36,7 @@ public class FrontController {
} }
private Command getCommand(String request) { private Command getCommand(String request) {
Class<?> commandClass = getCommandClass(request); Class commandClass = getCommandClass(request);
try { try {
return (Command) commandClass.newInstance(); return (Command) commandClass.newInstance();
} catch (Exception e) { } catch (Exception e) {
@ -44,8 +44,8 @@ public class FrontController {
} }
} }
private static Class<?> getCommandClass(String request) { private static Class getCommandClass(String request) {
Class<?> result; Class result;
try { try {
result = Class.forName("com.iluwatar.front.controller." + request + "Command"); result = Class.forName("com.iluwatar.front.controller." + request + "Command");
} catch (ClassNotFoundException e) { } catch (ClassNotFoundException e) {

View File

@ -34,7 +34,7 @@ import static org.junit.jupiter.api.Assertions.assertSame;
public class ApplicationExceptionTest { public class ApplicationExceptionTest {
@Test @Test
public void testCause() { public void testCause() throws Exception {
final Exception cause = new Exception(); final Exception cause = new Exception();
assertSame(cause, new ApplicationException(cause).getCause()); assertSame(cause, new ApplicationException(cause).getCause());
} }

View File

@ -41,7 +41,7 @@ public class GuardedQueueTest {
GuardedQueue g = new GuardedQueue(); GuardedQueue g = new GuardedQueue();
ExecutorService executorService = Executors.newFixedThreadPool(2); ExecutorService executorService = Executors.newFixedThreadPool(2);
executorService.submit(() -> value = g.get()); executorService.submit(() -> value = g.get());
executorService.submit(() -> g.put(10)); executorService.submit(() -> g.put(Integer.valueOf(10)));
executorService.shutdown(); executorService.shutdown();
try { try {
executorService.awaitTermination(30, TimeUnit.SECONDS); executorService.awaitTermination(30, TimeUnit.SECONDS);

View File

@ -34,7 +34,7 @@ import java.util.concurrent.ExecutionException;
public class AppTest { public class AppTest {
@Test @Test
public void test() { public void test() throws InterruptedException, ExecutionException {
App.main(null); App.main(null);
} }
} }

View File

@ -22,7 +22,6 @@
*/ */
package com.iluwatar.halfsynchalfasync; package com.iluwatar.halfsynchalfasync;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.mockito.InOrder; import org.mockito.InOrder;
@ -45,17 +44,11 @@ import static org.mockito.Mockito.when;
* @author Jeroen Meulemeester * @author Jeroen Meulemeester
*/ */
public class AsynchronousServiceTest { public class AsynchronousServiceTest {
private AsynchronousService service;
private AsyncTask<Object> task;
@BeforeEach
public void setUp() {
service = new AsynchronousService(new LinkedBlockingQueue<>());
task = mock(AsyncTask.class);
}
@Test @Test
public void testPerfectExecution() throws Exception { public void testPerfectExecution() throws Exception {
final AsynchronousService service = new AsynchronousService(new LinkedBlockingQueue<>());
final AsyncTask<Object> task = mock(AsyncTask.class);
final Object result = new Object(); final Object result = new Object();
when(task.call()).thenReturn(result); when(task.call()).thenReturn(result);
service.execute(task); service.execute(task);
@ -72,6 +65,8 @@ public class AsynchronousServiceTest {
@Test @Test
public void testCallException() throws Exception { public void testCallException() throws Exception {
final AsynchronousService service = new AsynchronousService(new LinkedBlockingQueue<>());
final AsyncTask<Object> task = mock(AsyncTask.class);
final IOException exception = new IOException(); final IOException exception = new IOException();
when(task.call()).thenThrow(exception); when(task.call()).thenThrow(exception);
service.execute(task); service.execute(task);
@ -87,7 +82,9 @@ public class AsynchronousServiceTest {
} }
@Test @Test
public void testPreCallException() { public void testPreCallException() throws Exception {
final AsynchronousService service = new AsynchronousService(new LinkedBlockingQueue<>());
final AsyncTask<Object> task = mock(AsyncTask.class);
final IllegalStateException exception = new IllegalStateException(); final IllegalStateException exception = new IllegalStateException();
doThrow(exception).when(task).onPreCall(); doThrow(exception).when(task).onPreCall();
service.execute(task); service.execute(task);

View File

@ -22,6 +22,9 @@
*/ */
package com.iluwatar.intercepting.filter; package com.iluwatar.intercepting.filter;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import javax.swing.JButton; import javax.swing.JButton;
import javax.swing.JFrame; import javax.swing.JFrame;
import javax.swing.JLabel; import javax.swing.JLabel;
@ -30,9 +33,6 @@ import javax.swing.JRootPane;
import javax.swing.JTextArea; import javax.swing.JTextArea;
import javax.swing.JTextField; import javax.swing.JTextField;
import javax.swing.SwingUtilities; import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
import java.awt.BorderLayout;
import java.awt.GridLayout;
/** /**
* The Client class is responsible for handling the input and running them through filters inside the * The Client class is responsible for handling the input and running them through filters inside the
@ -60,7 +60,7 @@ public class Client extends JFrame { // NOSONAR
*/ */
public Client() { public Client() {
super("Client System"); super("Client System");
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(300, 300); setSize(300, 300);
jl = new JLabel("RUNNING..."); jl = new JLabel("RUNNING...");
jtFields = new JTextField[3]; jtFields = new JTextField[3];

View File

@ -22,6 +22,11 @@
*/ */
package com.iluwatar.intercepting.filter; package com.iluwatar.intercepting.filter;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton; import javax.swing.JButton;
import javax.swing.JFrame; import javax.swing.JFrame;
import javax.swing.JPanel; import javax.swing.JPanel;
@ -29,12 +34,7 @@ import javax.swing.JRootPane;
import javax.swing.JScrollPane; import javax.swing.JScrollPane;
import javax.swing.JTable; import javax.swing.JTable;
import javax.swing.SwingUtilities; import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
import javax.swing.table.DefaultTableModel; import javax.swing.table.DefaultTableModel;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
/** /**
* This is where the requests are displayed after being validated by filters. * This is where the requests are displayed after being validated by filters.
@ -47,6 +47,7 @@ public class Target extends JFrame { //NOSONAR
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
private JTable jt; private JTable jt;
private JScrollPane jsp;
private DefaultTableModel dtm; private DefaultTableModel dtm;
private JButton del; private JButton del;
@ -55,7 +56,7 @@ public class Target extends JFrame { //NOSONAR
*/ */
public Target() { public Target() {
super("Order System"); super("Order System");
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(640, 480); setSize(640, 480);
dtm = dtm =
new DefaultTableModel(new Object[] {"Name", "Contact Number", "Address", "Deposit Number", new DefaultTableModel(new Object[] {"Name", "Contact Number", "Address", "Deposit Number",
@ -72,7 +73,7 @@ public class Target extends JFrame { //NOSONAR
bot.setLayout(new BorderLayout()); bot.setLayout(new BorderLayout());
bot.add(del, BorderLayout.EAST); bot.add(del, BorderLayout.EAST);
add(bot, BorderLayout.SOUTH); add(bot, BorderLayout.SOUTH);
JScrollPane jsp = new JScrollPane(jt); jsp = new JScrollPane(jt);
jsp.setPreferredSize(new Dimension(500, 250)); jsp.setPreferredSize(new Dimension(500, 250));
add(jsp, BorderLayout.CENTER); add(jsp, BorderLayout.CENTER);

View File

@ -40,7 +40,7 @@ import static org.mockito.Mockito.when;
public class FilterManagerTest { public class FilterManagerTest {
@Test @Test
public void testFilterRequest() { public void testFilterRequest() throws Exception {
final Target target = mock(Target.class); final Target target = mock(Target.class);
final FilterManager filterManager = new FilterManager(); final FilterManager filterManager = new FilterManager();
assertEquals("RUNNING...", filterManager.filterRequest(mock(Order.class))); assertEquals("RUNNING...", filterManager.filterRequest(mock(Order.class)));
@ -48,7 +48,7 @@ public class FilterManagerTest {
} }
@Test @Test
public void testAddFilter() { public void testAddFilter() throws Exception {
final Target target = mock(Target.class); final Target target = mock(Target.class);
final FilterManager filterManager = new FilterManager(); final FilterManager filterManager = new FilterManager();

View File

@ -89,7 +89,7 @@ public class FilterTest {
@ParameterizedTest @ParameterizedTest
@MethodSource("getTestData") @MethodSource("getTestData")
public void testExecute(Filter filter, Order order, String expectedResult) { public void testExecute(Filter filter, Order order, String expectedResult) throws Exception {
final String result = filter.execute(order); final String result = filter.execute(order);
assertNotNull(result); assertNotNull(result);
assertEquals(expectedResult, result.trim()); assertEquals(expectedResult, result.trim());
@ -97,7 +97,7 @@ public class FilterTest {
@ParameterizedTest @ParameterizedTest
@MethodSource("getTestData") @MethodSource("getTestData")
public void testNext(Filter filter) { public void testNext(Filter filter) throws Exception {
assertNull(filter.getNext()); assertNull(filter.getNext());
assertSame(filter, filter.getLast()); assertSame(filter, filter.getLast());
} }

View File

@ -36,35 +36,35 @@ public class OrderTest {
private static final String EXPECTED_VALUE = "test"; private static final String EXPECTED_VALUE = "test";
@Test @Test
public void testSetName() { public void testSetName() throws Exception {
final Order order = new Order(); final Order order = new Order();
order.setName(EXPECTED_VALUE); order.setName(EXPECTED_VALUE);
assertEquals(EXPECTED_VALUE, order.getName()); assertEquals(EXPECTED_VALUE, order.getName());
} }
@Test @Test
public void testSetContactNumber() { public void testSetContactNumber() throws Exception {
final Order order = new Order(); final Order order = new Order();
order.setContactNumber(EXPECTED_VALUE); order.setContactNumber(EXPECTED_VALUE);
assertEquals(EXPECTED_VALUE, order.getContactNumber()); assertEquals(EXPECTED_VALUE, order.getContactNumber());
} }
@Test @Test
public void testSetAddress() { public void testSetAddress() throws Exception {
final Order order = new Order(); final Order order = new Order();
order.setAddress(EXPECTED_VALUE); order.setAddress(EXPECTED_VALUE);
assertEquals(EXPECTED_VALUE, order.getAddress()); assertEquals(EXPECTED_VALUE, order.getAddress());
} }
@Test @Test
public void testSetDepositNumber() { public void testSetDepositNumber() throws Exception {
final Order order = new Order(); final Order order = new Order();
order.setDepositNumber(EXPECTED_VALUE); order.setDepositNumber(EXPECTED_VALUE);
assertEquals(EXPECTED_VALUE, order.getDepositNumber()); assertEquals(EXPECTED_VALUE, order.getDepositNumber());
} }
@Test @Test
public void testSetOrder() { public void testSetOrder() throws Exception {
final Order order = new Order(); final Order order = new Order();
order.setOrderItem(EXPECTED_VALUE); order.setOrderItem(EXPECTED_VALUE);
assertEquals(EXPECTED_VALUE, order.getOrderItem()); assertEquals(EXPECTED_VALUE, order.getOrderItem());

View File

@ -50,49 +50,49 @@ class BstIteratorTest {
@Test @Test
void nextForEmptyTree() { void nextForEmptyTree() {
BstIterator<Integer> iter = new BstIterator<>(emptyRoot); BstIterator iter = new BstIterator<>(emptyRoot);
assertThrows(NoSuchElementException.class, iter::next, assertThrows(NoSuchElementException.class, iter::next,
"next() should throw an IllegalStateException if hasNext() is false."); "next() should throw an IllegalStateException if hasNext() is false.");
} }
@Test @Test
void nextOverEntirePopulatedTree() { void nextOverEntirePopulatedTree() {
BstIterator<Integer> iter = new BstIterator<>(nonEmptyRoot); BstIterator iter = new BstIterator<>(nonEmptyRoot);
assertEquals(Integer.valueOf(1), iter.next().getVal(), "First Node is 1."); assertEquals(1, iter.next().getVal(), "First Node is 1.");
assertEquals(Integer.valueOf(3), iter.next().getVal(), "Second Node is 3."); assertEquals(3, iter.next().getVal(), "Second Node is 3.");
assertEquals(Integer.valueOf(4), iter.next().getVal(), "Third Node is 4."); assertEquals(4, iter.next().getVal(), "Third Node is 4.");
assertEquals(Integer.valueOf(5), iter.next().getVal(), "Fourth Node is 5."); assertEquals(5, iter.next().getVal(), "Fourth Node is 5.");
assertEquals(Integer.valueOf(6), iter.next().getVal(), "Fifth Node is 6."); assertEquals(6, iter.next().getVal(), "Fifth Node is 6.");
assertEquals(Integer.valueOf(7), iter.next().getVal(), "Sixth Node is 7."); assertEquals(7, iter.next().getVal(), "Sixth Node is 7.");
} }
@Test @Test
void hasNextForEmptyTree() { void hasNextForEmptyTree() {
BstIterator<Integer> iter = new BstIterator<>(emptyRoot); BstIterator iter = new BstIterator<>(emptyRoot);
assertFalse(iter.hasNext(), "hasNext() should return false for empty tree."); assertFalse(iter.hasNext(), "hasNext() should return false for empty tree.");
} }
@Test @Test
void hasNextForPopulatedTree() { void hasNextForPopulatedTree() {
BstIterator<Integer> iter = new BstIterator<>(nonEmptyRoot); BstIterator iter = new BstIterator<>(nonEmptyRoot);
assertTrue(iter.hasNext(), "hasNext() should return true for populated tree."); assertTrue(iter.hasNext(), "hasNext() should return true for populated tree.");
} }
@Test @Test
void nextAndHasNextOverEntirePopulatedTree() { void nextAndHasNextOverEntirePopulatedTree() {
BstIterator<Integer> iter = new BstIterator<>(nonEmptyRoot); BstIterator iter = new BstIterator<>(nonEmptyRoot);
assertTrue(iter.hasNext(), "Iterator hasNext() should be true."); assertTrue(iter.hasNext(), "Iterator hasNext() should be true.");
assertEquals(Integer.valueOf(1), iter.next().getVal(), "First Node is 1."); assertEquals(1, iter.next().getVal(), "First Node is 1.");
assertTrue(iter.hasNext(), "Iterator hasNext() should be true."); assertTrue(iter.hasNext(), "Iterator hasNext() should be true.");
assertEquals(Integer.valueOf(3), iter.next().getVal(), "Second Node is 3."); assertEquals(3, iter.next().getVal(), "Second Node is 3.");
assertTrue(iter.hasNext(), "Iterator hasNext() should be true."); assertTrue(iter.hasNext(), "Iterator hasNext() should be true.");
assertEquals(Integer.valueOf(4), iter.next().getVal(), "Third Node is 4."); assertEquals(4, iter.next().getVal(), "Third Node is 4.");
assertTrue(iter.hasNext(), "Iterator hasNext() should be true."); assertTrue(iter.hasNext(), "Iterator hasNext() should be true.");
assertEquals(Integer.valueOf(5), iter.next().getVal(), "Fourth Node is 5."); assertEquals(5, iter.next().getVal(), "Fourth Node is 5.");
assertTrue(iter.hasNext(), "Iterator hasNext() should be true."); assertTrue(iter.hasNext(), "Iterator hasNext() should be true.");
assertEquals(Integer.valueOf(6), iter.next().getVal(), "Fifth Node is 6."); assertEquals(6, iter.next().getVal(), "Fifth Node is 6.");
assertTrue(iter.hasNext(), "Iterator hasNext() should be true."); assertTrue(iter.hasNext(), "Iterator hasNext() should be true.");
assertEquals(Integer.valueOf(7), iter.next().getVal(), "Sixth Node is 7."); assertEquals(7, iter.next().getVal(), "Sixth Node is 7.");
assertFalse(iter.hasNext(), "Iterator hasNext() should be false, end of tree."); assertFalse(iter.hasNext(), "Iterator hasNext() should be false, end of tree.");
} }

View File

@ -41,6 +41,6 @@ public class CakeViewImpl implements View {
} }
public void render() { public void render() {
cakeBakingService.getAllCakes().forEach(cake -> LOGGER.info(cake.toString())); cakeBakingService.getAllCakes().stream().forEach(cake -> LOGGER.info(cake.toString()));
} }
} }

View File

@ -35,14 +35,14 @@ import static org.junit.jupiter.api.Assertions.assertNull;
public class CakeBakingExceptionTest { public class CakeBakingExceptionTest {
@Test @Test
public void testConstructor() { public void testConstructor() throws Exception {
final CakeBakingException exception = new CakeBakingException(); final CakeBakingException exception = new CakeBakingException();
assertNull(exception.getMessage()); assertNull(exception.getMessage());
assertNull(exception.getCause()); assertNull(exception.getCause());
} }
@Test @Test
public void testConstructorWithMessage() { public void testConstructorWithMessage() throws Exception {
final String expectedMessage = "message"; final String expectedMessage = "message";
final CakeBakingException exception = new CakeBakingException(expectedMessage); final CakeBakingException exception = new CakeBakingException(expectedMessage);
assertEquals(expectedMessage, exception.getMessage()); assertEquals(expectedMessage, exception.getMessage());

View File

@ -42,7 +42,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
public class CakeBakingServiceImplTest { public class CakeBakingServiceImplTest {
@Test @Test
public void testLayers() { public void testLayers() throws CakeBakingException {
final CakeBakingServiceImpl service = new CakeBakingServiceImpl(); final CakeBakingServiceImpl service = new CakeBakingServiceImpl();
final List<CakeLayerInfo> initialLayers = service.getAvailableLayers(); final List<CakeLayerInfo> initialLayers = service.getAvailableLayers();
@ -65,7 +65,7 @@ public class CakeBakingServiceImplTest {
} }
@Test @Test
public void testToppings() { public void testToppings() throws CakeBakingException {
final CakeBakingServiceImpl service = new CakeBakingServiceImpl(); final CakeBakingServiceImpl service = new CakeBakingServiceImpl();
final List<CakeToppingInfo> initialToppings = service.getAvailableToppings(); final List<CakeToppingInfo> initialToppings = service.getAvailableToppings();
@ -125,7 +125,7 @@ public class CakeBakingServiceImplTest {
} }
@Test @Test
public void testBakeCakeMissingTopping() { public void testBakeCakeMissingTopping() throws CakeBakingException {
final CakeBakingServiceImpl service = new CakeBakingServiceImpl(); final CakeBakingServiceImpl service = new CakeBakingServiceImpl();
final CakeLayerInfo layer1 = new CakeLayerInfo("Layer1", 1000); final CakeLayerInfo layer1 = new CakeLayerInfo("Layer1", 1000);
@ -140,7 +140,7 @@ public class CakeBakingServiceImplTest {
} }
@Test @Test
public void testBakeCakeMissingLayer() { public void testBakeCakeMissingLayer() throws CakeBakingException {
final CakeBakingServiceImpl service = new CakeBakingServiceImpl(); final CakeBakingServiceImpl service = new CakeBakingServiceImpl();
final List<CakeInfo> initialCakes = service.getAllCakes(); final List<CakeInfo> initialCakes = service.getAllCakes();

View File

@ -44,7 +44,7 @@ public class CakeTest {
final Cake cake = new Cake(); final Cake cake = new Cake();
assertNull(cake.getId()); assertNull(cake.getId());
final Long expectedId = 1234L; final Long expectedId = Long.valueOf(1234L);
cake.setId(expectedId); cake.setId(expectedId);
assertEquals(expectedId, cake.getId()); assertEquals(expectedId, cake.getId());
} }

View File

@ -37,7 +37,7 @@ public class Java8Holder {
private static final Logger LOGGER = LoggerFactory.getLogger(Java8Holder.class); private static final Logger LOGGER = LoggerFactory.getLogger(Java8Holder.class);
private Supplier<Heavy> heavy = this::createAndCacheHeavy; private Supplier<Heavy> heavy = () -> createAndCacheHeavy();
public Java8Holder() { public Java8Holder() {
LOGGER.info("Java8Holder created"); LOGGER.info("Java8Holder created");

View File

@ -27,7 +27,6 @@ import java.io.FileReader;
import java.io.IOException; import java.io.IOException;
import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
/** /**
* The Module pattern can be considered a Creational pattern and a Structural pattern. It manages * The Module pattern can be considered a Creational pattern and a Structural pattern. It manages
@ -89,7 +88,7 @@ public final class FileLoggerModuleTest {
fileLoggerModule.prepare(); fileLoggerModule.prepare();
/* Test if nothing is printed in file */ /* Test if nothing is printed in file */
assertNull(readFirstLine(OUTPUT_FILE)); assertEquals(readFirstLine(OUTPUT_FILE), null);
/* Unprepare to cleanup the modules */ /* Unprepare to cleanup the modules */
fileLoggerModule.unprepare(); fileLoggerModule.unprepare();
@ -114,7 +113,7 @@ public final class FileLoggerModuleTest {
fileLoggerModule.printErrorString(ERROR); fileLoggerModule.printErrorString(ERROR);
/* Test if 'Message' is printed in file */ /* Test if 'Message' is printed in file */
assertEquals(ERROR, readFirstLine(ERROR_FILE)); assertEquals(readFirstLine(ERROR_FILE), ERROR);
/* Unprepare to cleanup the modules */ /* Unprepare to cleanup the modules */
fileLoggerModule.unprepare(); fileLoggerModule.unprepare();
@ -136,7 +135,7 @@ public final class FileLoggerModuleTest {
fileLoggerModule.prepare(); fileLoggerModule.prepare();
/* Test if nothing is printed in file */ /* Test if nothing is printed in file */
assertNull(readFirstLine(ERROR_FILE)); assertEquals(readFirstLine(ERROR_FILE), null);
/* Unprepare to cleanup the modules */ /* Unprepare to cleanup the modules */
fileLoggerModule.unprepare(); fileLoggerModule.unprepare();
@ -151,7 +150,11 @@ public final class FileLoggerModuleTest {
private static final String readFirstLine(final String file) { private static final String readFirstLine(final String file) {
String firstLine = null; String firstLine = null;
try (BufferedReader bufferedReader = new BufferedReader(new FileReader(file))) { BufferedReader bufferedReader = null;
try {
/* Create a buffered reader */
bufferedReader = new BufferedReader(new FileReader(file));
while (bufferedReader.ready()) { while (bufferedReader.ready()) {
@ -163,6 +166,15 @@ public final class FileLoggerModuleTest {
} catch (final IOException e) { } catch (final IOException e) {
LOGGER.error("ModuleTest::readFirstLine()", e); LOGGER.error("ModuleTest::readFirstLine()", e);
} finally {
if (bufferedReader != null) {
try {
bufferedReader.close();
} catch (final IOException e) {
LOGGER.error("ModuleTest::readFirstLine()", e);
}
}
} }
return firstLine; return firstLine;

View File

@ -34,31 +34,33 @@ import java.util.List;
*/ */
public class LoadBalancer { public class LoadBalancer {
private static final List<Server> SERVERS = new ArrayList<>(); private static List<Server> servers = new ArrayList<>();
private static int lastServedId; private static int lastServedId;
static { static {
int id = 0; int id = 0;
for (int port : new int[] {8080, 8081, 8082, 8083, 8084}) { servers.add(new Server("localhost", 8081, ++id));
SERVERS.add(new Server("localhost", port, ++id)); servers.add(new Server("localhost", 8080, ++id));
} servers.add(new Server("localhost", 8082, ++id));
servers.add(new Server("localhost", 8083, ++id));
servers.add(new Server("localhost", 8084, ++id));
} }
/** /**
* Add new server * Add new server
*/ */
public final void addServer(Server server) { public final void addServer(Server server) {
synchronized (SERVERS) { synchronized (servers) {
SERVERS.add(server); servers.add(server);
} }
} }
public final int getNoOfServers() { public final int getNoOfServers() {
return SERVERS.size(); return servers.size();
} }
public int getLastServedId() { public static int getLastServedId() {
return lastServedId; return lastServedId;
} }
@ -66,10 +68,10 @@ public class LoadBalancer {
* Handle request * Handle request
*/ */
public synchronized void serverRequest(Request request) { public synchronized void serverRequest(Request request) {
if (lastServedId >= SERVERS.size()) { if (lastServedId >= servers.size()) {
lastServedId = 0; lastServedId = 0;
} }
Server server = SERVERS.get(lastServedId++); Server server = servers.get(lastServedId++);
server.serve(request); server.serve(request);
} }

View File

@ -22,7 +22,9 @@
*/ */
package com.iluwatar.monostate; package com.iluwatar.monostate;
import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Matchers.any; import static org.mockito.Matchers.any;
import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
@ -32,8 +34,6 @@ import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.verifyZeroInteractions; import static org.mockito.Mockito.verifyZeroInteractions;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
import org.junit.jupiter.api.Test;
/** /**
* Date: 12/21/15 - 12:26 PM * Date: 12/21/15 - 12:26 PM
* *
@ -47,9 +47,9 @@ public class LoadBalancerTest {
final LoadBalancer secondBalancer = new LoadBalancer(); final LoadBalancer secondBalancer = new LoadBalancer();
firstBalancer.addServer(new Server("localhost", 8085, 6)); firstBalancer.addServer(new Server("localhost", 8085, 6));
// Both should have the same number of servers. // Both should have the same number of servers.
assertEquals(firstBalancer.getNoOfServers(), secondBalancer.getNoOfServers()); assertTrue(firstBalancer.getNoOfServers() == secondBalancer.getNoOfServers());
// Both Should have the same LastServedId // Both Should have the same LastServedId
assertEquals(firstBalancer.getLastServedId(), secondBalancer.getLastServedId()); assertTrue(firstBalancer.getLastServedId() == secondBalancer.getLastServedId());
} }
@Test @Test

View File

@ -45,27 +45,27 @@ public class MuteTest {
@Test @Test
public void muteShouldRunTheCheckedRunnableAndNotThrowAnyExceptionIfCheckedRunnableDoesNotThrowAnyException() { public void muteShouldRunTheCheckedRunnableAndNotThrowAnyExceptionIfCheckedRunnableDoesNotThrowAnyException() {
Mute.mute(this::methodNotThrowingAnyException); Mute.mute(() -> methodNotThrowingAnyException());
} }
@Test @Test
public void muteShouldRethrowUnexpectedExceptionAsAssertionError() { public void muteShouldRethrowUnexpectedExceptionAsAssertionError() throws Exception {
assertThrows(AssertionError.class, () -> { assertThrows(AssertionError.class, () -> {
Mute.mute(this::methodThrowingException); Mute.mute(() -> methodThrowingException());
}); });
} }
@Test @Test
public void loggedMuteShouldRunTheCheckedRunnableAndNotThrowAnyExceptionIfCheckedRunnableDoesNotThrowAnyException() { public void loggedMuteShouldRunTheCheckedRunnableAndNotThrowAnyExceptionIfCheckedRunnableDoesNotThrowAnyException() {
Mute.loggedMute(this::methodNotThrowingAnyException); Mute.loggedMute(() -> methodNotThrowingAnyException());
} }
@Test @Test
public void loggedMuteShouldLogExceptionTraceBeforeSwallowingIt() { public void loggedMuteShouldLogExceptionTraceBeforeSwallowingIt() throws IOException {
ByteArrayOutputStream stream = new ByteArrayOutputStream(); ByteArrayOutputStream stream = new ByteArrayOutputStream();
System.setErr(new PrintStream(stream)); System.setErr(new PrintStream(stream));
Mute.loggedMute(this::methodThrowingException); Mute.loggedMute(() -> methodThrowingException());
assertTrue(new String(stream.toByteArray()).contains(MESSAGE)); assertTrue(new String(stream.toByteArray()).contains(MESSAGE));
} }

View File

@ -56,7 +56,7 @@ public class NullNodeTest {
} }
@Test @Test
public void testWalk() { public void testWalk() throws Exception {
NullNode.getInstance().walk(); NullNode.getInstance().walk();
} }

View File

@ -110,7 +110,7 @@ public class TreeTest {
} }
@Test @Test
public void testGetLeft() { public void testGetLeft() throws Exception {
final Node level1 = TREE_ROOT.getLeft(); final Node level1 = TREE_ROOT.getLeft();
assertNotNull(level1); assertNotNull(level1);
assertEquals("level1_a", level1.getName()); assertEquals("level1_a", level1.getName());
@ -130,7 +130,7 @@ public class TreeTest {
} }
@Test @Test
public void testGetRight() { public void testGetRight() throws Exception {
final Node level1 = TREE_ROOT.getRight(); final Node level1 = TREE_ROOT.getRight();
assertNotNull(level1); assertNotNull(level1);
assertEquals("level1_b", level1.getName()); assertEquals("level1_b", level1.getName());

View File

@ -59,7 +59,7 @@ public class King implements Royalty {
*/ */
public void flirt(Queen queen) { public void flirt(Queen queen) {
boolean flirtStatus = queen.getFlirted(this); boolean flirtStatus = queen.getFlirted(this);
if (!flirtStatus) { if (flirtStatus == false) {
this.makeUnhappy(); this.makeUnhappy();
} else { } else {
this.makeHappy(); this.makeHappy();

View File

@ -22,8 +22,6 @@
*/ */
package com.iluwatar.object.pool; package com.iluwatar.object.pool;
import java.util.concurrent.atomic.AtomicInteger;
/** /**
* *
* Oliphaunts are expensive to create * Oliphaunts are expensive to create
@ -31,7 +29,7 @@ import java.util.concurrent.atomic.AtomicInteger;
*/ */
public class Oliphaunt { public class Oliphaunt {
private static AtomicInteger counter = new AtomicInteger(0); private static int counter = 1;
private final int id; private final int id;
@ -39,7 +37,7 @@ public class Oliphaunt {
* Constructor * Constructor
*/ */
public Oliphaunt() { public Oliphaunt() {
id = counter.incrementAndGet(); id = counter++;
try { try {
Thread.sleep(1000); Thread.sleep(1000);
} catch (InterruptedException e) { } catch (InterruptedException e) {

View File

@ -49,23 +49,23 @@ public class OliphauntPoolTest {
public void testSubsequentCheckinCheckout() { public void testSubsequentCheckinCheckout() {
assertTimeout(ofMillis(5000), () -> { assertTimeout(ofMillis(5000), () -> {
final OliphauntPool pool = new OliphauntPool(); final OliphauntPool pool = new OliphauntPool();
assertEquals("Pool available=0 inUse=0", pool.toString()); assertEquals(pool.toString(), "Pool available=0 inUse=0");
final Oliphaunt expectedOliphaunt = pool.checkOut(); final Oliphaunt expectedOliphaunt = pool.checkOut();
assertEquals("Pool available=0 inUse=1", pool.toString()); assertEquals(pool.toString(), "Pool available=0 inUse=1");
pool.checkIn(expectedOliphaunt); pool.checkIn(expectedOliphaunt);
assertEquals("Pool available=1 inUse=0", pool.toString()); assertEquals(pool.toString(), "Pool available=1 inUse=0");
for (int i = 0; i < 100; i++) { for (int i = 0; i < 100; i++) {
final Oliphaunt oliphaunt = pool.checkOut(); final Oliphaunt oliphaunt = pool.checkOut();
assertEquals("Pool available=0 inUse=1", pool.toString()); assertEquals(pool.toString(), "Pool available=0 inUse=1");
assertSame(expectedOliphaunt, oliphaunt); assertSame(expectedOliphaunt, oliphaunt);
assertEquals(expectedOliphaunt.getId(), oliphaunt.getId()); assertEquals(expectedOliphaunt.getId(), oliphaunt.getId());
assertEquals(expectedOliphaunt.toString(), oliphaunt.toString()); assertEquals(expectedOliphaunt.toString(), oliphaunt.toString());
pool.checkIn(oliphaunt); pool.checkIn(oliphaunt);
assertEquals("Pool available=1 inUse=0", pool.toString()); assertEquals(pool.toString(), "Pool available=1 inUse=0");
} }
}); });
} }

View File

@ -42,7 +42,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
* @author Jeroen Meulemeester * @author Jeroen Meulemeester
*/ */
@TestInstance(TestInstance.Lifecycle.PER_CLASS) @TestInstance(TestInstance.Lifecycle.PER_CLASS)
public abstract class ObserverTest<O extends Observer<?, ?, WeatherType>> { public abstract class ObserverTest<O extends Observer> {
private InMemoryAppender appender; private InMemoryAppender appender;

View File

@ -36,34 +36,38 @@ import static org.junit.jupiter.api.Assertions.assertThrows;
public class PoisonMessageTest { public class PoisonMessageTest {
@Test @Test
public void testAddHeader() { public void testAddHeader() throws Exception {
assertThrows(UnsupportedOperationException.class, () -> { assertThrows(UnsupportedOperationException.class, () -> {
POISON_PILL.addHeader(Headers.SENDER, "sender"); POISON_PILL.addHeader(Headers.SENDER, "sender");
}); });
} }
@Test @Test
public void testGetHeader() { public void testGetHeader() throws Exception {
assertThrows(UnsupportedOperationException.class, () -> { assertThrows(UnsupportedOperationException.class, () -> {
POISON_PILL.getHeader(Headers.SENDER); POISON_PILL.getHeader(Headers.SENDER);
}); });
} }
@Test @Test
public void testGetHeaders() { public void testGetHeaders() throws Exception {
assertThrows(UnsupportedOperationException.class, POISON_PILL::getHeaders); assertThrows(UnsupportedOperationException.class, () -> {
POISON_PILL.getHeaders();
});
} }
@Test @Test
public void testSetBody() { public void testSetBody() throws Exception {
assertThrows(UnsupportedOperationException.class, () -> { assertThrows(UnsupportedOperationException.class, () -> {
POISON_PILL.setBody("Test message."); POISON_PILL.setBody("Test message.");
}); });
} }
@Test @Test
public void testGetBody() { public void testGetBody() throws Exception {
assertThrows(UnsupportedOperationException.class, POISON_PILL::getBody); assertThrows(UnsupportedOperationException.class, () -> {
POISON_PILL.getBody();
});
} }
} }

View File

@ -39,7 +39,7 @@ import static org.mockito.Mockito.verifyNoMoreInteractions;
public class ProducerTest { public class ProducerTest {
@Test @Test
public void testProduce() { public void testProduce() throws Exception {
assertTimeout(ofMillis(6000), () -> { assertTimeout(ofMillis(6000), () -> {
final ItemQueue queue = mock(ItemQueue.class); final ItemQueue queue = mock(ItemQueue.class);
final Producer producer = new Producer("producer", queue); final Producer producer = new Producer("producer", queue);

View File

@ -155,15 +155,19 @@ public class App {
* This is an async method and does not wait until the file is downloaded. * This is an async method and does not wait until the file is downloaded.
*/ */
private Promise<String> download(String urlString) { private Promise<String> download(String urlString) {
return new Promise<String>() Promise<String> downloadPromise = new Promise<String>()
.fulfillInAsync( .fulfillInAsync(
() -> Utility.downloadFile(urlString), executor) () -> {
return Utility.downloadFile(urlString);
}, executor)
.onError( .onError(
throwable -> { throwable -> {
throwable.printStackTrace(); throwable.printStackTrace();
taskCompleted(); taskCompleted();
} }
); );
return downloadPromise;
} }
private void stop() throws InterruptedException { private void stop() throws InterruptedException {

View File

@ -32,6 +32,7 @@ import java.io.FileWriter;
import java.io.IOException; import java.io.IOException;
import java.io.InputStreamReader; import java.io.InputStreamReader;
import java.io.Reader; import java.io.Reader;
import java.net.MalformedURLException;
import java.net.URL; import java.net.URL;
import java.util.HashMap; import java.util.HashMap;
import java.util.Iterator; import java.util.Iterator;
@ -110,7 +111,7 @@ public class Utility {
* Downloads the contents from the given urlString, and stores it in a temporary directory. * Downloads the contents from the given urlString, and stores it in a temporary directory.
* @return the absolute path of the file downloaded. * @return the absolute path of the file downloaded.
*/ */
public static String downloadFile(String urlString) throws IOException { public static String downloadFile(String urlString) throws MalformedURLException, IOException {
LOGGER.info("Downloading contents from url: {}", urlString); LOGGER.info("Downloading contents from url: {}", urlString);
URL url = new URL(urlString); URL url = new URL(urlString);
File file = File.createTempFile("promise_pattern", null); File file = File.createTempFile("promise_pattern", null);

View File

@ -76,8 +76,12 @@ public class PromiseTest {
private void testWaitingForeverForPromiseToBeFulfilled() private void testWaitingForeverForPromiseToBeFulfilled()
throws InterruptedException, TimeoutException { throws InterruptedException, TimeoutException {
Promise<Integer> promise = new Promise<>(); Promise<Integer> promise = new Promise<>();
promise.fulfillInAsync(() -> { promise.fulfillInAsync(new Callable<Integer>() {
@Override
public Integer call() throws Exception {
throw new RuntimeException("Barf!"); throw new RuntimeException("Barf!");
}
}, executor); }, executor);
try { try {
@ -100,8 +104,12 @@ public class PromiseTest {
private void testWaitingSomeTimeForPromiseToBeFulfilled() private void testWaitingSomeTimeForPromiseToBeFulfilled()
throws InterruptedException, TimeoutException { throws InterruptedException, TimeoutException {
Promise<Integer> promise = new Promise<>(); Promise<Integer> promise = new Promise<>();
promise.fulfillInAsync(() -> { promise.fulfillInAsync(new Callable<Integer>() {
@Override
public Integer call() throws Exception {
throw new RuntimeException("Barf!"); throw new RuntimeException("Barf!");
}
}, executor); }, executor);
try { try {
@ -142,8 +150,12 @@ public class PromiseTest {
throws InterruptedException, ExecutionException, TimeoutException { throws InterruptedException, ExecutionException, TimeoutException {
Promise<Void> dependentPromise = promise Promise<Void> dependentPromise = promise
.fulfillInAsync(new NumberCrunchingTask(), executor) .fulfillInAsync(new NumberCrunchingTask(), executor)
.thenAccept(value -> { .thenAccept(new Consumer<Integer>() {
@Override
public void accept(Integer value) {
throw new RuntimeException("Barf!"); throw new RuntimeException("Barf!");
}
}); });
try { try {
@ -186,8 +198,12 @@ public class PromiseTest {
throws InterruptedException, ExecutionException, TimeoutException { throws InterruptedException, ExecutionException, TimeoutException {
Promise<String> dependentPromise = promise Promise<String> dependentPromise = promise
.fulfillInAsync(new NumberCrunchingTask(), executor) .fulfillInAsync(new NumberCrunchingTask(), executor)
.thenApply(value -> { .thenApply(new Function<Integer, String>() {
@Override
public String apply(Integer value) {
throw new RuntimeException("Barf!"); throw new RuntimeException("Barf!");
}
}); });
try { try {

View File

@ -73,7 +73,7 @@ public class CharacterTest {
} }
@Test @Test
public void testToString() { public void testToString() throws Exception {
final Character prototype = new Character(); final Character prototype = new Character();
prototype.set(Stats.ARMOR, 1); prototype.set(Stats.ARMOR, 1);
prototype.set(Stats.AGILITY, 2); prototype.set(Stats.AGILITY, 2);
@ -91,7 +91,7 @@ public class CharacterTest {
} }
@Test @Test
public void testName() { public void testName() throws Exception {
final Character prototype = new Character(); final Character prototype = new Character();
prototype.set(Stats.ARMOR, 1); prototype.set(Stats.ARMOR, 1);
prototype.set(Stats.INTELLECT, 2); prototype.set(Stats.INTELLECT, 2);
@ -107,7 +107,7 @@ public class CharacterTest {
} }
@Test @Test
public void testType() { public void testType() throws Exception {
final Character prototype = new Character(); final Character prototype = new Character();
prototype.set(Stats.ARMOR, 1); prototype.set(Stats.ARMOR, 1);
prototype.set(Stats.INTELLECT, 2); prototype.set(Stats.INTELLECT, 2);

View File

@ -40,7 +40,7 @@ public class ElfBeast extends Beast {
} }
@Override @Override
public Beast copy() { public Beast copy() throws CloneNotSupportedException {
return new ElfBeast(this); return new ElfBeast(this);
} }

View File

@ -41,7 +41,7 @@ public class ElfMage extends Mage {
} }
@Override @Override
public ElfMage copy() { public ElfMage copy() throws CloneNotSupportedException {
return new ElfMage(this); return new ElfMage(this);
} }

View File

@ -40,7 +40,7 @@ public class ElfWarlord extends Warlord {
} }
@Override @Override
public ElfWarlord copy() { public ElfWarlord copy() throws CloneNotSupportedException {
return new ElfWarlord(this); return new ElfWarlord(this);
} }

View File

@ -40,7 +40,7 @@ public class OrcBeast extends Beast {
} }
@Override @Override
public Beast copy() { public Beast copy() throws CloneNotSupportedException {
return new OrcBeast(this); return new OrcBeast(this);
} }

View File

@ -40,7 +40,7 @@ public class OrcMage extends Mage {
} }
@Override @Override
public OrcMage copy() { public OrcMage copy() throws CloneNotSupportedException {
return new OrcMage(this); return new OrcMage(this);
} }

View File

@ -40,7 +40,7 @@ public class OrcWarlord extends Warlord {
} }
@Override @Override
public OrcWarlord copy() { public OrcWarlord copy() throws CloneNotSupportedException {
return new OrcWarlord(this); return new OrcWarlord(this);
} }

View File

@ -110,6 +110,8 @@ public class App {
LOGGER.info("Executor was shut down and Exiting."); LOGGER.info("Executor was shut down and Exiting.");
executor.shutdownNow(); executor.shutdownNow();
} }
} catch (InterruptedException ie) {
LOGGER.error(ie.getMessage());
} catch (Exception e) { } catch (Exception e) {
LOGGER.error(e.getMessage()); LOGGER.error(e.getMessage());
} }

View File

@ -58,6 +58,8 @@ public class ServiceExecutor implements Runnable {
Thread.sleep(1000); Thread.sleep(1000);
} }
} catch (InterruptedException ie) {
LOGGER.error(ie.getMessage());
} catch (Exception e) { } catch (Exception e) {
LOGGER.error(e.getMessage()); LOGGER.error(e.getMessage());
} }

View File

@ -80,6 +80,8 @@ public class TaskGenerator implements Task, Runnable {
// Make the current thread to sleep after every Message submission. // Make the current thread to sleep after every Message submission.
Thread.sleep(1000); Thread.sleep(1000);
} }
} catch (InterruptedException ie) {
LOGGER.error(ie.getMessage());
} catch (Exception e) { } catch (Exception e) {
LOGGER.error(e.getMessage()); LOGGER.error(e.getMessage());
} }

View File

@ -42,7 +42,7 @@ public class MessageQueueTest {
msgQueue.submitMsg(new Message("MessageQueue Test")); msgQueue.submitMsg(new Message("MessageQueue Test"));
// retrieve message // retrieve message
assertEquals("MessageQueue Test", msgQueue.retrieveMsg().getMsg()); assertEquals(msgQueue.retrieveMsg().getMsg(), "MessageQueue Test");
} }
} }

View File

@ -39,6 +39,6 @@ public class MessageTest {
// Parameterized constructor test. // Parameterized constructor test.
String testMsg = "Message Test"; String testMsg = "Message Test";
Message msg = new Message(testMsg); Message msg = new Message(testMsg);
assertEquals(testMsg, msg.getMsg()); assertEquals(msg.getMsg(), testMsg);
} }
} }

View File

@ -22,6 +22,14 @@
*/ */
package com.iluwatar.repository; package com.iluwatar.repository;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.sql.DataSource;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
@ -30,13 +38,6 @@ import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.test.context.support.AnnotationConfigContextLoader; import org.springframework.test.context.support.AnnotationConfigContextLoader;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
import javax.sql.DataSource;
import java.sql.ResultSet;
import java.sql.SQLException;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
/** /**
* This case is Just for test the Annotation Based configuration * This case is Just for test the Annotation Based configuration
* *
@ -69,7 +70,7 @@ public class AppConfigTest {
result = resultSet.getString(1); result = resultSet.getString(1);
} }
assertEquals(expected, result); assertTrue(result.equals(expected));
} }
} }

View File

@ -31,7 +31,7 @@ import java.io.IOException;
*/ */
public class AppTest { public class AppTest {
@Test @Test
public void test() { public void test() throws IOException {
String[] args = {}; String[] args = {};
App.main(args); App.main(args);
} }

View File

@ -109,7 +109,9 @@ public class RepositoryTest {
List<Person> persons = repository.findAll(new PersonSpecifications.AgeBetweenSpec(20, 40)); List<Person> persons = repository.findAll(new PersonSpecifications.AgeBetweenSpec(20, 40));
assertEquals(3, persons.size()); assertEquals(3, persons.size());
assertTrue(persons.stream().allMatch(item -> item.getAge() > 20 && item.getAge() < 40)); assertTrue(persons.stream().allMatch((item) -> {
return item.getAge() > 20 && item.getAge() < 40;
}));
} }
@Test @Test

View File

@ -53,7 +53,7 @@ public class FindCustomerTest {
* @throws Exception the expected exception * @throws Exception the expected exception
*/ */
@Test @Test
public void oneException() { public void oneException() throws Exception {
assertThrows(BusinessException.class, () -> { assertThrows(BusinessException.class, () -> {
new FindCustomer("123", new BusinessException("test")).perform(); new FindCustomer("123", new BusinessException("test")).perform();
}); });

View File

@ -40,7 +40,7 @@ public class RetryTest {
* Should contain all errors thrown. * Should contain all errors thrown.
*/ */
@Test @Test
public void errors() { public void errors() throws Exception {
final BusinessException e = new BusinessException("unhandled"); final BusinessException e = new BusinessException("unhandled");
final Retry<String> retry = new Retry<>( final Retry<String> retry = new Retry<>(
() -> { throw e; }, () -> { throw e; },

View File

@ -31,7 +31,7 @@ import java.io.IOException;
*/ */
public class AppTest { public class AppTest {
@Test @Test
public void test() { public void test() throws IOException {
String[] args = {}; String[] args = {};
App.main(args); App.main(args);
} }

View File

@ -37,16 +37,16 @@ public class FruitBowlTest {
public void fruitBowlTest() { public void fruitBowlTest() {
FruitBowl fbowl = new FruitBowl(); FruitBowl fbowl = new FruitBowl();
assertEquals(0, fbowl.countFruit()); assertEquals(fbowl.countFruit(), 0);
for (int i = 1; i <= 10; i++) { for (int i = 1; i <= 10; i++) {
fbowl.put(new Fruit(Fruit.FruitType.LEMON)); fbowl.put(new Fruit(Fruit.FruitType.LEMON));
assertEquals(i, fbowl.countFruit()); assertEquals(fbowl.countFruit(), i);
} }
for (int i = 9; i >= 0; i--) { for (int i = 9; i >= 0; i--) {
assertNotNull(fbowl.take()); assertNotNull(fbowl.take());
assertEquals(i, fbowl.countFruit()); assertEquals(fbowl.countFruit(), i);
} }
assertNull(fbowl.take()); assertNull(fbowl.take());

View File

@ -36,12 +36,12 @@ public class SemaphoreTest {
public void acquireReleaseTest() { public void acquireReleaseTest() {
Semaphore sphore = new Semaphore(3); Semaphore sphore = new Semaphore(3);
assertEquals(3, sphore.getAvailableLicenses()); assertEquals(sphore.getAvailableLicenses(), 3);
for (int i = 2; i >= 0; i--) { for (int i = 2; i >= 0; i--) {
try { try {
sphore.acquire(); sphore.acquire();
assertEquals(i, sphore.getAvailableLicenses()); assertEquals(sphore.getAvailableLicenses(), i);
} catch (InterruptedException e) { } catch (InterruptedException e) {
fail(e.toString()); fail(e.toString());
} }
@ -49,10 +49,10 @@ public class SemaphoreTest {
for (int i = 1; i <= 3; i++) { for (int i = 1; i <= 3; i++) {
sphore.release(); sphore.release();
assertEquals(i, sphore.getAvailableLicenses()); assertEquals(sphore.getAvailableLicenses(), i);
} }
sphore.release(); sphore.release();
assertEquals(3, sphore.getAvailableLicenses()); assertEquals(sphore.getAvailableLicenses(), 3);
} }
} }

View File

@ -36,7 +36,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
public class QueenTest { public class QueenTest {
@Test @Test
public void testNotFlirtyUncomplemented() { public void testNotFlirtyUncomplemented() throws Exception {
final Queen queen = new Queen(); final Queen queen = new Queen();
queen.setFlirtiness(false); queen.setFlirtiness(false);
queen.changeMood(); queen.changeMood();
@ -44,7 +44,7 @@ public class QueenTest {
} }
@Test @Test
public void testNotFlirtyComplemented() { public void testNotFlirtyComplemented() throws Exception {
final Queen queen = new Queen(); final Queen queen = new Queen();
queen.setFlirtiness(false); queen.setFlirtiness(false);
queen.receiveCompliments(); queen.receiveCompliments();
@ -53,14 +53,14 @@ public class QueenTest {
} }
@Test @Test
public void testFlirtyUncomplemented() { public void testFlirtyUncomplemented() throws Exception {
final Queen queen = new Queen(); final Queen queen = new Queen();
queen.changeMood(); queen.changeMood();
assertFalse(queen.getMood()); assertFalse(queen.getMood());
} }
@Test @Test
public void testFlirtyComplemented() { public void testFlirtyComplemented() throws Exception {
final Queen queen = new Queen(); final Queen queen = new Queen();
queen.receiveCompliments(); queen.receiveCompliments();
queen.changeMood(); queen.changeMood();

View File

@ -41,7 +41,7 @@ import static org.mockito.Mockito.when;
public class ServantTest { public class ServantTest {
@Test @Test
public void testFeed() { public void testFeed() throws Exception {
final Royalty royalty = mock(Royalty.class); final Royalty royalty = mock(Royalty.class);
final Servant servant = new Servant("test"); final Servant servant = new Servant("test");
servant.feed(royalty); servant.feed(royalty);
@ -50,7 +50,7 @@ public class ServantTest {
} }
@Test @Test
public void testGiveWine() { public void testGiveWine() throws Exception {
final Royalty royalty = mock(Royalty.class); final Royalty royalty = mock(Royalty.class);
final Servant servant = new Servant("test"); final Servant servant = new Servant("test");
servant.giveWine(royalty); servant.giveWine(royalty);
@ -59,7 +59,7 @@ public class ServantTest {
} }
@Test @Test
public void testGiveCompliments() { public void testGiveCompliments() throws Exception {
final Royalty royalty = mock(Royalty.class); final Royalty royalty = mock(Royalty.class);
final Servant servant = new Servant("test"); final Servant servant = new Servant("test");
servant.giveCompliments(royalty); servant.giveCompliments(royalty);
@ -68,7 +68,7 @@ public class ServantTest {
} }
@Test @Test
public void testCheckIfYouWillBeHanged() { public void testCheckIfYouWillBeHanged() throws Exception {
final Royalty goodMoodRoyalty = mock(Royalty.class); final Royalty goodMoodRoyalty = mock(Royalty.class);
when(goodMoodRoyalty.getMood()).thenReturn(true); when(goodMoodRoyalty.getMood()).thenReturn(true);

Some files were not shown because too many files have changed in this diff Show More