Fixed most reported issues by SonarCloud.

This commit is contained in:
Toxic Dreamz 2020-08-15 21:47:39 +04:00
parent e7e3ace01f
commit 31471acb69
190 changed files with 1426 additions and 661 deletions

View File

@ -25,14 +25,23 @@ package com.iluwatar.abstractdocument;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
/** /**
* Simple App test * Simple App test
*/ */
public class AppTest { class AppTest {
/**
* Issue: Add at least one assertion to this test case.
*
* Solution: Inserted assertion to check whether the execution of the main method in {@link App}
* throws an exception.
*/
@Test @Test
public void shouldExecuteAppWithoutException() { void shouldExecuteAppWithoutException() {
App.main(null); assertDoesNotThrow(() -> App.main(null));
} }
} }

View File

@ -25,12 +25,23 @@ package com.iluwatar.abstractfactory;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
/** /**
* Tests that Abstract Factory example runs without errors. * Tests that Abstract Factory example runs without errors.
*/ */
public class AppTest { class AppTest {
/**
* Issue: Add at least one assertion to this test case.
*
* Solution: Inserted assertion to check whether the execution of the main method in {@link App}
* throws an exception.
*/
@Test @Test
public void test() { void shouldExecuteApplicationWithoutException() {
App.main(new String[]{});
assertDoesNotThrow(() -> App.main(new String[]{}));
} }
} }

View File

@ -25,13 +25,23 @@ package com.iluwatar.acyclicvisitor;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
/** /**
* Tests that the Acyclic Visitor example runs without errors. * Tests that the Acyclic Visitor example runs without errors.
*/ */
public class AppTest { class AppTest {
/**
* Issue: Add at least one assertion to this test case.
*
* Solution: Inserted assertion to check whether the execution of the main method in {@link App}
* throws an exception.
*/
@Test @Test
public void test() { void shouldExecuteApplicationWithoutException() {
App.main(new String[]{});
assertDoesNotThrow(() -> App.main(new String[]{}));
} }
} }

View File

@ -25,12 +25,23 @@ package com.iluwatar.adapter;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
/** /**
* Tests that Adapter example runs without errors. * Tests that Adapter example runs without errors.
*/ */
public class AppTest { class AppTest {
/**
* Issue: Add at least one assertion to this test case.
*
* Solution: Inserted assertion to check whether the execution of the main method in {@link App}
* throws an exception.
*/
@Test @Test
public void test() { void shouldExecuteApplicationWithoutException() {
App.main(new String[]{});
assertDoesNotThrow(() -> App.main(new String[]{}));
} }
} }

View File

@ -62,7 +62,7 @@ public class RemoteService implements RemoteServiceInterface {
* *
* @param value integer value to be multiplied. * @param value integer value to be multiplied.
* @return if waitTime is less than {@link RemoteService#THRESHOLD}, it returns value * 10, * @return if waitTime is less than {@link RemoteService#THRESHOLD}, it returns value * 10,
* otherwise {@link RemoteServiceInterface#FAILURE}. * otherwise {@link RemoteServiceStatus#FAILURE}.
*/ */
@Override @Override
public long doRemoteFunction(int value) { public long doRemoteFunction(int value) {
@ -74,6 +74,6 @@ public class RemoteService implements RemoteServiceInterface {
} catch (InterruptedException e) { } catch (InterruptedException e) {
LOGGER.error("Thread sleep state interrupted", e); LOGGER.error("Thread sleep state interrupted", e);
} }
return waitTime <= THRESHOLD ? value * 10 : FAILURE; return waitTime <= THRESHOLD ? value * 10 : RemoteServiceStatus.FAILURE.getRemoteServiceStatusValue();
} }
} }

View File

@ -27,7 +27,6 @@ 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); long doRemoteFunction(int value);
} }

View File

@ -0,0 +1,23 @@
package com.iluwatar.ambassador;
/**
* Holds information regarding the status of the Remote Service.
*
* !Attention - This Enum replaces the integer value previously stored in {@link RemoteServiceInterface}
* as SonarCloud was identifying it as an issue. All test cases have been checked after changes, without failures.
*/
public enum RemoteServiceStatus {
FAILURE(-1)
;
private final long remoteServiceStatusValue;
RemoteServiceStatus(long remoteServiceStatusValue) {
this.remoteServiceStatusValue = remoteServiceStatusValue;
}
public long getRemoteServiceStatusValue() {
return remoteServiceStatusValue;
}
}

View File

@ -23,6 +23,7 @@
package com.iluwatar.ambassador; package com.iluwatar.ambassador;
import static com.iluwatar.ambassador.RemoteServiceStatus.FAILURE;
import static java.lang.Thread.sleep; import static java.lang.Thread.sleep;
import org.slf4j.Logger; import org.slf4j.Logger;
@ -58,14 +59,14 @@ public class ServiceAmbassador implements RemoteServiceInterface {
private long safeCall(int value) { private long safeCall(int value) {
var retries = 0; var retries = 0;
var result = (long) FAILURE; var result = FAILURE.getRemoteServiceStatusValue();
for (int i = 0; i < RETRIES; i++) { for (int i = 0; i < RETRIES; i++) {
if (retries >= RETRIES) { if (retries >= RETRIES) {
return FAILURE; return FAILURE.getRemoteServiceStatusValue();
} }
if ((result = checkLatency(value)) == FAILURE) { if ((result = checkLatency(value)) == FAILURE.getRemoteServiceStatusValue()) {
LOGGER.info("Failed to reach remote: (" + (i + 1) + ")"); LOGGER.info("Failed to reach remote: (" + (i + 1) + ")");
retries++; retries++;
try { try {

View File

@ -25,13 +25,23 @@ package com.iluwatar.ambassador;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
/** /**
* Application test * Application test
*/ */
class AppTest { class AppTest {
/**
* Issue: Add at least one assertion to this test case.
*
* Solution: Inserted assertion to check whether the execution of the main method in {@link App}
* throws an exception.
*/
@Test @Test
void test() { void shouldExecuteApplicationWithoutException() {
App.main(new String[]{});
assertDoesNotThrow(() -> App.main(new String[]{}));
} }
} }

View File

@ -37,6 +37,6 @@ class ClientTest {
Client client = new Client(); Client client = new Client();
var result = client.useService(10); var result = client.useService(10);
assertTrue(result == 100 || result == RemoteService.FAILURE); assertTrue(result == 100 || result == RemoteServiceStatus.FAILURE.getRemoteServiceStatusValue());
} }
} }

View File

@ -37,7 +37,7 @@ class RemoteServiceTest {
void testFailedCall() { void testFailedCall() {
var remoteService = new RemoteService(new StaticRandomProvider(0.21)); var remoteService = new RemoteService(new StaticRandomProvider(0.21));
var result = remoteService.doRemoteFunction(10); var result = remoteService.doRemoteFunction(10);
assertEquals(RemoteServiceInterface.FAILURE, result); assertEquals(RemoteServiceStatus.FAILURE.getRemoteServiceStatusValue(), result);
} }
@Test @Test

View File

@ -35,6 +35,6 @@ class ServiceAmbassadorTest {
@Test @Test
void test() { void test() {
long result = new ServiceAmbassador().doRemoteFunction(10); long result = new ServiceAmbassador().doRemoteFunction(10);
assertTrue(result == 100 || result == RemoteServiceInterface.FAILURE); assertTrue(result == 100 || result == RemoteServiceStatus.FAILURE.getRemoteServiceStatusValue());
} }
} }

View File

@ -25,12 +25,24 @@ package com.iluwatar.async.method.invocation;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
/** /**
* Application test * Application test
*/ */
class AppTest { class AppTest {
/**
* Issue: Add at least one assertion to this test case.
*
* Solution: Inserted assertion to check whether the execution of the main method in {@link App}
* throws an exception.
*/
@Test @Test
void test() throws Exception { void shouldExecuteApplicationWithoutException() {
App.main(new String[]{});
assertDoesNotThrow(() -> App.main(new String[]{}));
} }
} }

View File

@ -24,15 +24,26 @@
package com.iluwatar.balking; package com.iluwatar.balking;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.function.Executable;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
/** /**
* Application test * Application test
*/ */
class AppTest { class AppTest {
/**
* Issue: Add at least one assertion to this test case.
*
* Solution: Inserted assertion to check whether the execution of the main method in {@link App}
* throws an exception.
*/
@Test @Test
void main() { void shouldExecuteApplicationWithoutException() {
App.main(); assertDoesNotThrow((Executable) App::main);
} }
} }

View File

@ -25,12 +25,22 @@ package com.iluwatar.bridge;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
/** /**
* Application test * Application test
*/ */
class AppTest { class AppTest {
/**
* Issue: Add at least one assertion to this test case.
*
* Solution: Inserted assertion to check whether the execution of the main method in {@link App}
* throws an exception.
*/
@Test @Test
void test() { void shouldExecuteApplicationWithoutException() {
App.main(new String[]{}); assertDoesNotThrow(() -> App.main(new String[]{}));
} }
} }

View File

@ -25,12 +25,23 @@ package com.iluwatar.builder;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
/** /**
* Application test * Application test
*/ */
class AppTest { class AppTest {
/**
* Issue: Add at least one assertion to this test case.
*
* Solution: Inserted assertion to check whether the execution of the main method in {@link App}
* throws an exception.
*/
@Test @Test
void test() { void shouldExecuteApplicationWithoutException() {
App.main(new String[]{});
assertDoesNotThrow(() -> App.main(new String[]{}));
} }
} }

View File

@ -27,13 +27,23 @@ import org.junit.jupiter.api.Test;
import java.io.IOException; import java.io.IOException;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
/** /**
* Tests that Business Delegate example runs without errors. * Tests that Business Delegate example runs without errors.
*/ */
public class AppTest { class AppTest {
/**
* Issue: Add at least one assertion to this test case.
*
* Solution: Inserted assertion to check whether the execution of the main method in {@link App}
* throws an exception.
*/
@Test @Test
public void test() throws IOException { void shouldExecuteApplicationWithoutException() {
String[] args = {};
App.main(args); assertDoesNotThrow(() -> App.main(new String[]{}));
} }
} }

View File

@ -58,12 +58,14 @@ public class App {
var vm = new VirtualMachine(); var vm = new VirtualMachine();
vm.getWizards()[0] = wizard; vm.getWizards()[0] = wizard;
interpretInstruction("LITERAL 0", vm); String literal = "LITERAL 0";
interpretInstruction("LITERAL 0", vm);
interpretInstruction(literal, vm);
interpretInstruction(literal, vm);
interpretInstruction("GET_HEALTH", vm); interpretInstruction("GET_HEALTH", vm);
interpretInstruction("LITERAL 0", vm); interpretInstruction(literal, vm);
interpretInstruction("GET_AGILITY", vm); interpretInstruction("GET_AGILITY", vm);
interpretInstruction("LITERAL 0", vm); interpretInstruction(literal, vm);
interpretInstruction("GET_WISDOM ", vm); interpretInstruction("GET_WISDOM ", vm);
interpretInstruction("ADD", vm); interpretInstruction("ADD", vm);
interpretInstruction("LITERAL 2", vm); interpretInstruction("LITERAL 2", vm);

View File

@ -25,13 +25,22 @@ package com.iluwatar.bytecode;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
/** /**
* Application test * Application test
*/ */
public class AppTest { class AppTest {
/**
* Issue: Add at least one assertion to this test case.
*
* Solution: Inserted assertion to check whether the execution of the main method in {@link App}
* throws an exception.
*/
@Test @Test
public void test() { void shouldExecuteApplicationWithoutException() {
App.main(new String[]{}); assertDoesNotThrow(() -> App.main(new String[]{}));
} }
} }

View File

@ -27,12 +27,23 @@ import org.junit.jupiter.api.Test;
import java.io.IOException; import java.io.IOException;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
/** /**
* Tests that Caching example runs without errors. * Tests that Caching example runs without errors.
*/ */
public class AppTest { class AppTest {
/**
* Issue: Add at least one assertion to this test case.
*
* Solution: Inserted assertion to check whether the execution of the main method in {@link App}
* throws an exception.
*/
@Test @Test
public void test() { void shouldExecuteApplicationWithoutException() {
App.main(new String[]{});
assertDoesNotThrow(() -> App.main(new String[]{}));
} }
} }

View File

@ -25,12 +25,23 @@ package com.iluwatar.callback;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
/** /**
* Tests that Callback example runs without errors. * Tests that Callback example runs without errors.
*/ */
public class AppTest { class AppTest {
/**
* Issue: Add at least one assertion to this test case.
*
* Solution: Inserted assertion to check whether the execution of the main method in {@link App}
* throws an exception.
*/
@Test @Test
public void test() { void shouldExecuteApplicationWithoutException() {
App.main(new String[]{});
assertDoesNotThrow(() -> App.main(new String[]{}));
} }
} }

View File

@ -25,13 +25,23 @@ package com.iluwatar.chain;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
/** /**
* Application test * Application test
*/ */
public class AppTest { class AppTest {
/**
* Issue: Add at least one assertion to this test case.
*
* Solution: Inserted assertion to check whether the execution of the main method in {@link App}
* throws an exception.
*/
@Test @Test
public void test() { void shouldExecuteApplicationWithoutException() {
App.main(new String[]{});
assertDoesNotThrow(() -> App.main(new String[]{}));
} }
} }

View File

@ -39,6 +39,12 @@
<artifactId>junit</artifactId> <artifactId>junit</artifactId>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<scope>test</scope>
</dependency>
</dependencies> </dependencies>
</project> </project>

View File

@ -25,12 +25,19 @@ package com.iluwatar.combinator;
import org.junit.Test; import org.junit.Test;
import static org.junit.Assert.*; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
public class CombinatorAppTest { public class CombinatorAppTest {
/**
* Issue: Add at least one assertion to this test case.
*
* Solution: Inserted assertion to check whether the execution of the main method in {@link CombinatorApp#main(String[])}
* throws an exception.
*/
@Test @Test
public void main() { public void shouldExecuteApplicationWithoutException() {
CombinatorApp.main(new String[]{}); assertDoesNotThrow(() -> CombinatorApp.main(new String[]{}));
} }
} }

View File

@ -25,12 +25,21 @@ package com.iluwatar.command;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
/** /**
* Tests that Command example runs without errors. * Tests that Command example runs without errors.
*/ */
public class AppTest { class AppTest {
/**
* Issue: Add at least one assertion to this test case.
*
* Solution: Inserted assertion to check whether the execution of the main method in {@link App#main(String[])}
* throws an exception.
*/
@Test @Test
public void test() { void shouldExecuteApplicationWithoutException() {
App.main(new String[]{});
assertDoesNotThrow(() -> App.main(new String[]{}));
} }
} }

View File

@ -39,6 +39,8 @@ import com.iluwatar.commander.shippingservice.ShippingService;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import java.util.List;
/** /**
* <p>Commander pattern is used to handle all issues that can come up while making a * <p>Commander pattern is used to handle all issues that can come up while making a
* distributed transaction. The idea is to have a commander, which coordinates the execution of all * distributed transaction. The idea is to have a commander, which coordinates the execution of all
@ -159,8 +161,8 @@ public class Commander {
private void sendPaymentRequest(Order order) { private void sendPaymentRequest(Order order) {
if (System.currentTimeMillis() - order.createdTime >= this.paymentTime) { if (System.currentTimeMillis() - order.createdTime >= this.paymentTime) {
if (order.paid.equals(PaymentStatus.Trying)) { if (order.paid.equals(PaymentStatus.TRYING)) {
order.paid = PaymentStatus.NotDone; order.paid = PaymentStatus.NOT_DONE;
sendPaymentFailureMessage(order); sendPaymentFailureMessage(order);
LOG.error("Order " + order.id + ": Payment time for order over, failed and returning.."); LOG.error("Order " + order.id + ": Payment time for order over, failed and returning..");
} //if succeeded or failed, would have been dequeued, no attempt to make payment } //if succeeded or failed, would have been dequeued, no attempt to make payment
@ -169,53 +171,10 @@ public class Commander {
var list = paymentService.exceptionsList; var list = paymentService.exceptionsList;
var t = new Thread(() -> { var t = new Thread(() -> {
Retry.Operation op = (l) -> { Retry.Operation op = (l) -> {
if (!l.isEmpty()) { handlePaymentRetryOperation(order, l);
if (DatabaseUnavailableException.class.isAssignableFrom(l.get(0).getClass())) {
LOG.debug("Order " + order.id + ": Error in connecting to payment service,"
+ " trying again..");
} else {
LOG.debug("Order " + order.id + ": Error in creating payment request..");
}
throw l.remove(0);
}
if (order.paid.equals(PaymentStatus.Trying)) {
var transactionId = paymentService.receiveRequest(order.price);
order.paid = PaymentStatus.Done;
LOG.info("Order " + order.id + ": Payment successful, transaction Id: " + transactionId);
if (!finalSiteMsgShown) {
LOG.info("Payment made successfully, thank you for shopping with us!!");
finalSiteMsgShown = true;
}
sendSuccessMessage(order);
}
}; };
Retry.HandleErrorIssue<Order> handleError = (o, err) -> { Retry.HandleErrorIssue<Order> handleError = (o, err) -> {
if (PaymentDetailsErrorException.class.isAssignableFrom(err.getClass())) { handlePaymentErrorIssue(order, o, err);
if (!finalSiteMsgShown) {
LOG.info("There was an error in payment. Your account/card details "
+ "may have been incorrect. "
+ "Meanwhile, your order has been converted to COD and will be shipped.");
finalSiteMsgShown = true;
}
LOG.error("Order " + order.id + ": Payment details incorrect, failed..");
o.paid = PaymentStatus.NotDone;
sendPaymentFailureMessage(o);
} else {
if (o.messageSent.equals(MessageSent.NoneSent)) {
if (!finalSiteMsgShown) {
LOG.info("There was an error in payment. We are on it, and will get back to you "
+ "asap. Don't worry, your order has been placed and will be shipped.");
finalSiteMsgShown = true;
}
LOG.warn("Order " + order.id + ": Payment error, going to queue..");
sendPaymentPossibleErrorMsg(o);
}
if (o.paid.equals(PaymentStatus.Trying) && System
.currentTimeMillis() - o.createdTime < paymentTime) {
var qt = new QueueTask(o, TaskType.Payment, -1);
updateQueue(qt);
}
}
}; };
var r = new Retry<>(op, handleError, numOfRetries, retryDuration, var r = new Retry<>(op, handleError, numOfRetries, retryDuration,
e -> DatabaseUnavailableException.class.isAssignableFrom(e.getClass())); e -> DatabaseUnavailableException.class.isAssignableFrom(e.getClass()));
@ -228,18 +187,70 @@ public class Commander {
t.start(); t.start();
} }
private void handlePaymentRetryOperation(Order order, List<Exception> l) throws Exception {
if (!l.isEmpty()) {
if (DatabaseUnavailableException.class.isAssignableFrom(l.get(0).getClass())) {
LOG.debug("Order " + order.id + ": Error in connecting to payment service,"
+ " trying again..");
} else {
LOG.debug("Order " + order.id + ": Error in creating payment request..");
}
throw l.remove(0);
}
if (order.paid.equals(PaymentStatus.TRYING)) {
var transactionId = paymentService.receiveRequest(order.price);
order.paid = PaymentStatus.DONE;
LOG.info("Order " + order.id + ": Payment successful, transaction Id: " + transactionId);
if (!finalSiteMsgShown) {
LOG.info("Payment made successfully, thank you for shopping with us!!");
finalSiteMsgShown = true;
}
sendSuccessMessage(order);
}
}
private void handlePaymentErrorIssue(Order order, Order o, Exception err) {
if (PaymentDetailsErrorException.class.isAssignableFrom(err.getClass())) {
if (!finalSiteMsgShown) {
LOG.info("There was an error in payment. Your account/card details "
+ "may have been incorrect. "
+ "Meanwhile, your order has been converted to COD and will be shipped.");
finalSiteMsgShown = true;
}
LOG.error("Order " + order.id + ": Payment details incorrect, failed..");
o.paid = PaymentStatus.NOT_DONE;
sendPaymentFailureMessage(o);
} else {
if (o.messageSent.equals(MessageSent.NONE_SENT)) {
if (!finalSiteMsgShown) {
LOG.info("There was an error in payment. We are on it, and will get back to you "
+ "asap. Don't worry, your order has been placed and will be shipped.");
finalSiteMsgShown = true;
}
LOG.warn("Order " + order.id + ": Payment error, going to queue..");
sendPaymentPossibleErrorMsg(o);
}
if (o.paid.equals(PaymentStatus.TRYING) && System
.currentTimeMillis() - o.createdTime < paymentTime) {
var qt = new QueueTask(o, TaskType.PAYMENT, -1);
updateQueue(qt);
}
}
}
private void updateQueue(QueueTask qt) { private void updateQueue(QueueTask qt) {
if (System.currentTimeMillis() - qt.order.createdTime >= this.queueTime) { if (System.currentTimeMillis() - qt.order.createdTime >= this.queueTime) {
// since payment time is lesser than queuetime it would have already failed.. // since payment time is lesser than queuetime it would have already failed..
// additional check not needed // additional check not needed
LOG.trace("Order " + qt.order.id + ": Queue time for order over, failed.."); LOG.trace("Order " + qt.order.id + ": Queue time for order over, failed..");
return; return;
} else if (qt.taskType.equals(TaskType.Payment) && !qt.order.paid.equals(PaymentStatus.Trying) } else if (qt.taskType.equals(TaskType.PAYMENT) && !qt.order.paid.equals(PaymentStatus.TRYING)
|| qt.taskType.equals(TaskType.Messaging) && (qt.messageType == 1 || qt.taskType.equals(TaskType.MESSAGING) && (qt.messageType == 1
&& !qt.order.messageSent.equals(MessageSent.NoneSent) && !qt.order.messageSent.equals(MessageSent.NONE_SENT)
|| qt.order.messageSent.equals(MessageSent.PaymentFail) || qt.order.messageSent.equals(MessageSent.PAYMENT_FAIL)
|| qt.order.messageSent.equals(MessageSent.PaymentSuccessful)) || qt.order.messageSent.equals(MessageSent.PAYMENT_SUCCESSFUL))
|| qt.taskType.equals(TaskType.EmployeeDb) && qt.order.addedToEmployeeHandle) { || qt.taskType.equals(TaskType.EMPLOYEE_DB) && qt.order.addedToEmployeeHandle) {
LOG.trace("Order " + qt.order.id + ": Not queueing task since task already done.."); LOG.trace("Order " + qt.order.id + ": Not queueing task since task already done..");
return; return;
} }
@ -256,8 +267,8 @@ public class Commander {
tryDoingTasksInQueue(); tryDoingTasksInQueue();
}; };
Retry.HandleErrorIssue<QueueTask> handleError = (qt1, err) -> { Retry.HandleErrorIssue<QueueTask> handleError = (qt1, err) -> {
if (qt1.taskType.equals(TaskType.Payment)) { if (qt1.taskType.equals(TaskType.PAYMENT)) {
qt1.order.paid = PaymentStatus.NotDone; qt1.order.paid = PaymentStatus.NOT_DONE;
sendPaymentFailureMessage(qt1.order); sendPaymentFailureMessage(qt1.order);
LOG.error("Order " + qt1.order.id + ": Unable to enqueue payment task," LOG.error("Order " + qt1.order.id + ": Unable to enqueue payment task,"
+ " payment failed.."); + " payment failed..");
@ -331,7 +342,35 @@ public class Commander {
} }
var list = messagingService.exceptionsList; var list = messagingService.exceptionsList;
Thread t = new Thread(() -> { Thread t = new Thread(() -> {
Retry.Operation op = (l) -> { Retry.Operation op = handleSuccessMessageRetryOperation(order);
Retry.HandleErrorIssue<Order> handleError = (o, err) -> {
handleSuccessMessageErrorIssue(order, o);
};
var r = new Retry<>(op, handleError, numOfRetries, retryDuration,
e -> DatabaseUnavailableException.class.isAssignableFrom(e.getClass()));
try {
r.perform(list, order);
} catch (Exception e1) {
e1.printStackTrace();
}
});
t.start();
}
private void handleSuccessMessageErrorIssue(Order order, Order o) {
if ((o.messageSent.equals(MessageSent.NONE_SENT) || o.messageSent
.equals(MessageSent.PAYMENT_TRYING))
&& System.currentTimeMillis() - o.createdTime < messageTime) {
var qt = new QueueTask(order, TaskType.MESSAGING, 2);
updateQueue(qt);
LOG.info("Order " + order.id + ": Error in sending Payment Success message, trying to"
+ " queue task and add to employee handle..");
employeeHandleIssue(order);
}
}
private Retry.Operation handleSuccessMessageRetryOperation(Order order) {
return (l) -> {
if (!l.isEmpty()) { if (!l.isEmpty()) {
if (DatabaseUnavailableException.class.isAssignableFrom(l.get(0).getClass())) { if (DatabaseUnavailableException.class.isAssignableFrom(l.get(0).getClass())) {
LOG.debug("Order " + order.id + ": Error in connecting to messaging service " LOG.debug("Order " + order.id + ": Error in connecting to messaging service "
@ -342,34 +381,14 @@ public class Commander {
} }
throw l.remove(0); throw l.remove(0);
} }
if (!order.messageSent.equals(MessageSent.PaymentFail) if (!order.messageSent.equals(MessageSent.PAYMENT_FAIL)
&& !order.messageSent.equals(MessageSent.PaymentSuccessful)) { && !order.messageSent.equals(MessageSent.PAYMENT_SUCCESSFUL)) {
var requestId = messagingService.receiveRequest(2); var requestId = messagingService.receiveRequest(2);
order.messageSent = MessageSent.PaymentSuccessful; order.messageSent = MessageSent.PAYMENT_SUCCESSFUL;
LOG.info("Order " + order.id + ": Payment Success message sent," LOG.info("Order " + order.id + ": Payment Success message sent,"
+ " request Id: " + requestId); + " request Id: " + requestId);
} }
}; };
Retry.HandleErrorIssue<Order> handleError = (o, err) -> {
if ((o.messageSent.equals(MessageSent.NoneSent) || o.messageSent
.equals(MessageSent.PaymentTrying))
&& System.currentTimeMillis() - o.createdTime < messageTime) {
var qt = new QueueTask(order, TaskType.Messaging, 2);
updateQueue(qt);
LOG.info("Order " + order.id + ": Error in sending Payment Success message, trying to"
+ " queue task and add to employee handle..");
employeeHandleIssue(order);
}
};
var r = new Retry<>(op, handleError, numOfRetries, retryDuration,
e -> DatabaseUnavailableException.class.isAssignableFrom(e.getClass()));
try {
r.perform(list, order);
} catch (Exception e1) {
e1.printStackTrace();
}
});
t.start();
} }
private void sendPaymentFailureMessage(Order order) { private void sendPaymentFailureMessage(Order order) {
@ -380,34 +399,10 @@ public class Commander {
var list = messagingService.exceptionsList; var list = messagingService.exceptionsList;
var t = new Thread(() -> { var t = new Thread(() -> {
Retry.Operation op = (l) -> { Retry.Operation op = (l) -> {
if (!l.isEmpty()) { handlePaymentFailureRetryOperation(order, l);
if (DatabaseUnavailableException.class.isAssignableFrom(l.get(0).getClass())) {
LOG.debug("Order " + order.id + ": Error in connecting to messaging service "
+ "(Payment Failure msg), trying again..");
} else {
LOG.debug("Order " + order.id + ": Error in creating Payment Failure"
+ " message request..");
}
throw l.remove(0);
}
if (!order.messageSent.equals(MessageSent.PaymentFail)
&& !order.messageSent.equals(MessageSent.PaymentSuccessful)) {
var requestId = messagingService.receiveRequest(0);
order.messageSent = MessageSent.PaymentFail;
LOG.info("Order " + order.id + ": Payment Failure message sent successfully,"
+ " request Id: " + requestId);
}
}; };
Retry.HandleErrorIssue<Order> handleError = (o, err) -> { Retry.HandleErrorIssue<Order> handleError = (o, err) -> {
if ((o.messageSent.equals(MessageSent.NoneSent) || o.messageSent handlePaymentErrorIssue(order, o);
.equals(MessageSent.PaymentTrying))
&& System.currentTimeMillis() - o.createdTime < messageTime) {
var qt = new QueueTask(order, TaskType.Messaging, 0);
updateQueue(qt);
LOG.warn("Order " + order.id + ": Error in sending Payment Failure message, "
+ "trying to queue task and add to employee handle..");
employeeHandleIssue(o);
}
}; };
var r = new Retry<>(op, handleError, numOfRetries, retryDuration, var r = new Retry<>(op, handleError, numOfRetries, retryDuration,
e -> DatabaseUnavailableException.class.isAssignableFrom(e.getClass())); e -> DatabaseUnavailableException.class.isAssignableFrom(e.getClass()));
@ -420,6 +415,38 @@ public class Commander {
t.start(); t.start();
} }
private void handlePaymentErrorIssue(Order order, Order o) {
if ((o.messageSent.equals(MessageSent.NONE_SENT) || o.messageSent
.equals(MessageSent.PAYMENT_TRYING))
&& System.currentTimeMillis() - o.createdTime < messageTime) {
var qt = new QueueTask(order, TaskType.MESSAGING, 0);
updateQueue(qt);
LOG.warn("Order " + order.id + ": Error in sending Payment Failure message, "
+ "trying to queue task and add to employee handle..");
employeeHandleIssue(o);
}
}
private void handlePaymentFailureRetryOperation(Order order, List<Exception> l) throws Exception {
if (!l.isEmpty()) {
if (DatabaseUnavailableException.class.isAssignableFrom(l.get(0).getClass())) {
LOG.debug("Order " + order.id + ": Error in connecting to messaging service "
+ "(Payment Failure msg), trying again..");
} else {
LOG.debug("Order " + order.id + ": Error in creating Payment Failure"
+ " message request..");
}
throw l.remove(0);
}
if (!order.messageSent.equals(MessageSent.PAYMENT_FAIL)
&& !order.messageSent.equals(MessageSent.PAYMENT_SUCCESSFUL)) {
var requestId = messagingService.receiveRequest(0);
order.messageSent = MessageSent.PAYMENT_FAIL;
LOG.info("Order " + order.id + ": Payment Failure message sent successfully,"
+ " request Id: " + requestId);
}
}
private void sendPaymentPossibleErrorMsg(Order order) { private void sendPaymentPossibleErrorMsg(Order order) {
if (System.currentTimeMillis() - order.createdTime >= this.messageTime) { if (System.currentTimeMillis() - order.createdTime >= this.messageTime) {
LOG.trace("Message time for order over, returning.."); LOG.trace("Message time for order over, returning..");
@ -428,34 +455,10 @@ public class Commander {
var list = messagingService.exceptionsList; var list = messagingService.exceptionsList;
var t = new Thread(() -> { var t = new Thread(() -> {
Retry.Operation op = (l) -> { Retry.Operation op = (l) -> {
if (!l.isEmpty()) { handlePaymentPossibleErrorMsgRetryOperation(order, l);
if (DatabaseUnavailableException.class.isAssignableFrom(l.get(0).getClass())) {
LOG.debug("Order " + order.id + ": Error in connecting to messaging service "
+ "(Payment Error msg), trying again..");
} else {
LOG.debug("Order " + order.id + ": Error in creating Payment Error"
+ " messaging request..");
}
throw l.remove(0);
}
if (order.paid.equals(PaymentStatus.Trying) && order.messageSent
.equals(MessageSent.NoneSent)) {
var requestId = messagingService.receiveRequest(1);
order.messageSent = MessageSent.PaymentTrying;
LOG.info("Order " + order.id + ": Payment Error message sent successfully,"
+ " request Id: " + requestId);
}
}; };
Retry.HandleErrorIssue<Order> handleError = (o, err) -> { Retry.HandleErrorIssue<Order> handleError = (o, err) -> {
if (o.messageSent.equals(MessageSent.NoneSent) && order.paid handlePaymentPossibleErrorMsgErrorIssue(order, o);
.equals(PaymentStatus.Trying)
&& System.currentTimeMillis() - o.createdTime < messageTime) {
var qt = new QueueTask(order, TaskType.Messaging, 1);
updateQueue(qt);
LOG.warn("Order " + order.id + ": Error in sending Payment Error message, "
+ "trying to queue task and add to employee handle..");
employeeHandleIssue(o);
}
}; };
var r = new Retry<>(op, handleError, numOfRetries, retryDuration, var r = new Retry<>(op, handleError, numOfRetries, retryDuration,
e -> DatabaseUnavailableException.class.isAssignableFrom(e.getClass())); e -> DatabaseUnavailableException.class.isAssignableFrom(e.getClass()));
@ -468,6 +471,38 @@ public class Commander {
t.start(); t.start();
} }
private void handlePaymentPossibleErrorMsgErrorIssue(Order order, Order o) {
if (o.messageSent.equals(MessageSent.NONE_SENT) && order.paid
.equals(PaymentStatus.TRYING)
&& System.currentTimeMillis() - o.createdTime < messageTime) {
var qt = new QueueTask(order, TaskType.MESSAGING, 1);
updateQueue(qt);
LOG.warn("Order " + order.id + ": Error in sending Payment Error message, "
+ "trying to queue task and add to employee handle..");
employeeHandleIssue(o);
}
}
private void handlePaymentPossibleErrorMsgRetryOperation(Order order, List<Exception> l) throws Exception {
if (!l.isEmpty()) {
if (DatabaseUnavailableException.class.isAssignableFrom(l.get(0).getClass())) {
LOG.debug("Order " + order.id + ": Error in connecting to messaging service "
+ "(Payment Error msg), trying again..");
} else {
LOG.debug("Order " + order.id + ": Error in creating Payment Error"
+ " messaging request..");
}
throw l.remove(0);
}
if (order.paid.equals(PaymentStatus.TRYING) && order.messageSent
.equals(MessageSent.NONE_SENT)) {
var requestId = messagingService.receiveRequest(1);
order.messageSent = MessageSent.PAYMENT_TRYING;
LOG.info("Order " + order.id + ": Payment Error message sent successfully,"
+ " request Id: " + requestId);
}
}
private void employeeHandleIssue(Order order) { private void employeeHandleIssue(Order order) {
if (System.currentTimeMillis() - order.createdTime >= this.employeeTime) { if (System.currentTimeMillis() - order.createdTime >= this.employeeTime) {
LOG.trace("Order " + order.id + ": Employee handle time for order over, returning.."); LOG.trace("Order " + order.id + ": Employee handle time for order over, returning..");
@ -490,7 +525,7 @@ public class Commander {
Retry.HandleErrorIssue<Order> handleError = (o, err) -> { Retry.HandleErrorIssue<Order> handleError = (o, err) -> {
if (!o.addedToEmployeeHandle && System if (!o.addedToEmployeeHandle && System
.currentTimeMillis() - order.createdTime < employeeTime) { .currentTimeMillis() - order.createdTime < employeeTime) {
var qt = new QueueTask(order, TaskType.EmployeeDb, -1); var qt = new QueueTask(order, TaskType.EMPLOYEE_DB, -1);
updateQueue(qt); updateQueue(qt);
LOG.warn("Order " + order.id + ": Error in adding to employee db," LOG.warn("Order " + order.id + ": Error in adding to employee db,"
+ " trying to queue task.."); + " trying to queue task..");
@ -520,21 +555,21 @@ public class Commander {
LOG.trace("Order " + qt.order.id + ": This queue task of type " + qt.getType() LOG.trace("Order " + qt.order.id + ": This queue task of type " + qt.getType()
+ " does not need to be done anymore (timeout), dequeue.."); + " does not need to be done anymore (timeout), dequeue..");
} else { } else {
if (qt.taskType.equals(TaskType.Payment)) { if (qt.taskType.equals(TaskType.PAYMENT)) {
if (!qt.order.paid.equals(PaymentStatus.Trying)) { if (!qt.order.paid.equals(PaymentStatus.TRYING)) {
tryDequeue(); tryDequeue();
LOG.trace("Order " + qt.order.id + ": This payment task already done, dequeueing.."); LOG.trace("Order " + qt.order.id + ": This payment task already done, dequeueing..");
} else { } else {
sendPaymentRequest(qt.order); sendPaymentRequest(qt.order);
LOG.debug("Order " + qt.order.id + ": Trying to connect to payment service.."); LOG.debug("Order " + qt.order.id + ": Trying to connect to payment service..");
} }
} else if (qt.taskType.equals(TaskType.Messaging)) { } else if (qt.taskType.equals(TaskType.MESSAGING)) {
if (qt.order.messageSent.equals(MessageSent.PaymentFail) if (qt.order.messageSent.equals(MessageSent.PAYMENT_FAIL)
|| qt.order.messageSent.equals(MessageSent.PaymentSuccessful)) { || qt.order.messageSent.equals(MessageSent.PAYMENT_SUCCESSFUL)) {
tryDequeue(); tryDequeue();
LOG.trace("Order " + qt.order.id + ": This messaging task already done, dequeue.."); LOG.trace("Order " + qt.order.id + ": This messaging task already done, dequeue..");
} else if (qt.messageType == 1 && (!qt.order.messageSent.equals(MessageSent.NoneSent) } else if (qt.messageType == 1 && (!qt.order.messageSent.equals(MessageSent.NONE_SENT)
|| !qt.order.paid.equals(PaymentStatus.Trying))) { || !qt.order.paid.equals(PaymentStatus.TRYING))) {
tryDequeue(); tryDequeue();
LOG.trace("Order " + qt.order.id + ": This messaging task does not need to be done," LOG.trace("Order " + qt.order.id + ": This messaging task does not need to be done,"
+ " dequeue.."); + " dequeue..");
@ -548,7 +583,7 @@ public class Commander {
sendSuccessMessage(qt.order); sendSuccessMessage(qt.order);
LOG.debug("Order " + qt.order.id + ": Trying to connect to messaging service.."); LOG.debug("Order " + qt.order.id + ": Trying to connect to messaging service..");
} }
} else if (qt.taskType.equals(TaskType.EmployeeDb)) { } else if (qt.taskType.equals(TaskType.EMPLOYEE_DB)) {
if (qt.order.addedToEmployeeHandle) { if (qt.order.addedToEmployeeHandle) {
tryDequeue(); tryDequeue();
LOG.trace("Order " + qt.order.id + ": This employee handle task already done," LOG.trace("Order " + qt.order.id + ": This employee handle task already done,"

View File

@ -33,11 +33,11 @@ import java.util.Random;
public class Order { //can store all transactions ids also public class Order { //can store all transactions ids also
enum PaymentStatus { enum PaymentStatus {
NotDone, Trying, Done NOT_DONE, TRYING, DONE
} }
enum MessageSent { enum MessageSent {
NoneSent, PaymentFail, PaymentTrying, PaymentSuccessful NONE_SENT, PAYMENT_FAIL, PAYMENT_TRYING, PAYMENT_SUCCESSFUL
} }
final User user; final User user;
@ -65,8 +65,8 @@ public class Order { //can store all transactions ids also
} }
this.id = id; this.id = id;
USED_IDS.put(this.id, true); USED_IDS.put(this.id, true);
this.paid = PaymentStatus.Trying; this.paid = PaymentStatus.TRYING;
this.messageSent = MessageSent.NoneSent; this.messageSent = MessageSent.NONE_SENT;
this.addedToEmployeeHandle = false; this.addedToEmployeeHandle = false;
} }

View File

@ -38,7 +38,7 @@ public class MessagingService extends Service {
private static final Logger LOGGER = LoggerFactory.getLogger(MessagingService.class); private static final Logger LOGGER = LoggerFactory.getLogger(MessagingService.class);
enum MessageToSend { enum MessageToSend {
PaymentFail, PaymentTrying, PaymentSuccessful PAYMENT_FAIL, PAYMENT_TRYING, PAYMENT_SUCCESSFUL
} }
class MessageRequest { class MessageRequest {
@ -63,11 +63,11 @@ public class MessagingService extends Service {
var id = generateId(); var id = generateId();
MessageToSend msg; MessageToSend msg;
if (messageToSend == 0) { if (messageToSend == 0) {
msg = MessageToSend.PaymentFail; msg = MessageToSend.PAYMENT_FAIL;
} else if (messageToSend == 1) { } else if (messageToSend == 1) {
msg = MessageToSend.PaymentTrying; msg = MessageToSend.PAYMENT_TRYING;
} else { //messageToSend == 2 } else { //messageToSend == 2
msg = MessageToSend.PaymentSuccessful; msg = MessageToSend.PAYMENT_SUCCESSFUL;
} }
var req = new MessageRequest(id, msg); var req = new MessageRequest(id, msg);
return updateDb(req); return updateDb(req);
@ -84,10 +84,10 @@ public class MessagingService extends Service {
} }
String sendMessage(MessageToSend m) { String sendMessage(MessageToSend m) {
if (m.equals(MessageToSend.PaymentSuccessful)) { if (m.equals(MessageToSend.PAYMENT_SUCCESSFUL)) {
return "Msg: Your order has been placed and paid for successfully!" return "Msg: Your order has been placed and paid for successfully!"
+ " Thank you for shopping with us!"; + " Thank you for shopping with us!";
} else if (m.equals(MessageToSend.PaymentTrying)) { } else if (m.equals(MessageToSend.PAYMENT_TRYING)) {
return "Msg: There was an error in your payment process," return "Msg: There was an error in your payment process,"
+ " we are working on it and will return back to you shortly." + " we are working on it and will return back to you shortly."
+ " Meanwhile, your order has been placed and will be shipped."; + " Meanwhile, your order has been placed and will be shipped.";

View File

@ -36,7 +36,7 @@ public class QueueTask {
*/ */
public enum TaskType { public enum TaskType {
Messaging, Payment, EmployeeDb MESSAGING, PAYMENT, EMPLOYEE_DB
} }
public Order order; public Order order;
@ -68,7 +68,7 @@ public class QueueTask {
* @return String representing type of task * @return String representing type of task
*/ */
public String getType() { public String getType() {
if (!this.taskType.equals(TaskType.Messaging)) { if (!this.taskType.equals(TaskType.MESSAGING)) {
return this.taskType.toString(); return this.taskType.toString();
} else { } else {
if (this.messageType == 0) { if (this.messageType == 0) {

View File

@ -23,15 +23,23 @@
package com.iluwatar.composite; package com.iluwatar.composite;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
/** /**
* Application test * Application test
*/ */
public class AppTest { class AppTest {
/**
* Issue: Add at least one assertion to this test case.
*
* Solution: Inserted assertion to check whether the execution of the main method in {@link App#main(String[])}
* throws an exception.
*/
@Test @Test
public void test() { void shouldExecuteApplicationWithoutException() {
App.main(new String[]{}); Assertions.assertDoesNotThrow(() -> App.main(new String[]{}));
} }
} }

View File

@ -25,14 +25,24 @@ package com.iluwatar.converter;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
/** /**
* App running test * App running test
*/ */
public class AppTest { class AppTest {
/**
* Issue: Add at least one assertion to this test case.
*
* Solution: Inserted assertion to check whether the execution of the main method in {@link App#main(String[])}
* throws an exception.
*/
@Test @Test
public void testMain() { void shouldExecuteApplicationWithoutException() {
App.main(new String[]{});
assertDoesNotThrow(() -> App.main(new String[]{}));
} }
} }

View File

@ -25,12 +25,22 @@ package com.iluwatar.dao;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
/** /**
* Tests that DAO example runs without errors. * Tests that DAO example runs without errors.
*/ */
public class AppTest { class AppTest {
/**
* Issue: Add at least one assertion to this test case.
*
* Solution: Inserted assertion to check whether the execution of the main method in {@link App#main(String[])}
* throws an exception.
*/
@Test @Test
public void test() throws Exception { void shouldExecuteDaoWithoutException() {
App.main(new String[]{}); assertDoesNotThrow(() -> App.main(new String[]{}));
} }
} }

View File

@ -43,6 +43,6 @@ public class AiComponent implements Component {
@Override @Override
public void render() { public void render() {
// Do Nothing.
} }
} }

View File

@ -40,7 +40,7 @@ public class AiComponentManager {
private final int numEntities; private final int numEntities;
private static final Component[] AI_COMPONENTS = new AiComponent[MAX_ENTITIES]; private final Component[] AI_COMPONENTS = new AiComponent[MAX_ENTITIES];
public AiComponentManager(int numEntities) { public AiComponentManager(int numEntities) {
this.numEntities = numEntities; this.numEntities = numEntities;

View File

@ -40,7 +40,7 @@ public class PhysicsComponentManager {
private final int numEntities; private final int numEntities;
private static final Component[] PHYSICS_COMPONENTS = new PhysicsComponent[MAX_ENTITIES]; private final Component[] PHYSICS_COMPONENTS = new PhysicsComponent[MAX_ENTITIES];
public PhysicsComponentManager(int numEntities) { public PhysicsComponentManager(int numEntities) {
this.numEntities = numEntities; this.numEntities = numEntities;

View File

@ -40,7 +40,7 @@ public class RenderComponentManager {
private final int numEntities; private final int numEntities;
private static final Component[] RENDER_COMPONENTS = new RenderComponent[MAX_ENTITIES]; private final Component[] RENDER_COMPONENTS = new RenderComponent[MAX_ENTITIES];
public RenderComponentManager(int numEntities) { public RenderComponentManager(int numEntities) {
this.numEntities = numEntities; this.numEntities = numEntities;

View File

@ -26,16 +26,22 @@ package com.iluwatar.data.locality;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
/** /**
* Test Game Application * Test Game Application
*/ */
class ApplicationTest { class ApplicationTest {
/** /**
* Test run * Issue: Add at least one assertion to this test case.
*
* Solution: Inserted assertion to check whether the execution of the main method in {@link Application#main(String[])}
* throws an exception.
*/ */
@Test @Test
void main() { void shouldExecuteGameApplicationWithoutException() {
Application.main(new String[] {}); assertDoesNotThrow(() -> Application.main(new String[] {}));
} }
} }

View File

@ -24,14 +24,25 @@
package com.iluwatar.datamapper; package com.iluwatar.datamapper;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.function.Executable;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
/** /**
* Tests that Data-Mapper example runs without errors. * Tests that Data-Mapper example runs without errors.
*/ */
public final class AppTest { final class AppTest {
/**
* Issue: Add at least one assertion to this test case.
*
* Solution: Inserted assertion to check whether the execution of the main method in {@link App#main(String[])}
* throws an exception.
*/
@Test @Test
public void test() { void shouldExecuteApplicationWithoutException() {
App.main();
assertDoesNotThrow((Executable) App::main);
} }
} }

View File

@ -25,9 +25,19 @@ package com.iluwatar.datatransfer;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
public class AppTest { import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
class AppTest {
/**
* Issue: Add at least one assertion to this test case.
*
* Solution: Inserted assertion to check whether the execution of the main method in {@link App#main(String[])}
* throws an exception.
*/
@Test @Test
public void test() throws Exception { void shouldExecuteApplicationWithoutException() {
App.main(new String[]{}); assertDoesNotThrow(() -> App.main(new String[]{}));
} }
} }

View File

@ -25,13 +25,22 @@ package com.iluwatar.decorator;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
/** /**
* Application test * Application test
*/ */
public class AppTest { class AppTest {
/**
* Issue: Add at least one assertion to this test case.
*
* Solution: Inserted assertion to check whether the execution of the main method in {@link App#main(String[])}
* throws an exception.
*/
@Test @Test
public void test() { void shouldExecuteApplicationWithoutException() {
App.main(new String[]{}); assertDoesNotThrow(() -> App.main(new String[]{}));
} }
} }

View File

@ -25,14 +25,23 @@ package com.iluwatar.delegation.simple;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
/** /**
* Application Test Entry * Application Test Entry
*/ */
public class AppTest { class AppTest {
/**
* Issue: Add at least one assertion to this test case.
*
* Solution: Inserted assertion to check whether the execution of the main method in {@link App#main(String[])}
* throws an exception.
*/
@Test @Test
public void test() { void shouldExecuteApplicationWithoutException() {
App.main(new String[]{}); assertDoesNotThrow(() -> App.main(new String[]{}));
} }
} }

View File

@ -25,13 +25,22 @@ package com.iluwatar.dependency.injection;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
/** /**
* Application test * Application test
*/ */
public class AppTest { class AppTest {
/**
* Issue: Add at least one assertion to this test case.
*
* Solution: Inserted assertion to check whether the execution of the main method in {@link App#main(String[])}
* throws an exception.
*/
@Test @Test
public void test() { void shouldExecuteApplicationWithoutException() {
App.main(new String[]{}); assertDoesNotThrow(() -> App.main(new String[]{}));
} }
} }

View File

@ -26,12 +26,22 @@ package org.dirty.flag;
import com.iluwatar.dirtyflag.App; import com.iluwatar.dirtyflag.App;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
/** /**
* Tests that Dirty-Flag example runs without errors. * Tests that Dirty-Flag example runs without errors.
*/ */
public class AppTest { class AppTest {
/**
* Issue: Add at least one assertion to this test case.
*
* Solution: Inserted assertion to check whether the execution of the main method in {@link App#main(String[])}
* throws an exception.
*/
@Test @Test
public void test() { void shouldExecuteApplicationWithoutException() {
App.main(new String[]{}); assertDoesNotThrow(() -> App.main(new String[]{}));
} }
} }

View File

@ -44,6 +44,11 @@
<groupId>org.apache.commons</groupId> <groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId> <artifactId>commons-lang3</artifactId>
</dependency> </dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<scope>test</scope>
</dependency>
</dependencies> </dependencies>
<build> <build>
<plugins> <plugins>

View File

@ -25,14 +25,23 @@ package com.iluwatar.doublebuffer;
import org.junit.Test; import org.junit.Test;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
/** /**
* App unit test. * App unit test.
*/ */
public class AppTest { public class AppTest {
/**
* Issue: Add at least one assertion to this test case.
*
* Solution: Inserted assertion to check whether the execution of the main method in {@link App#main(String[])}
* throws an exception.
*/
@Test @Test
public void testMain() { public void shouldExecuteApplicationWithoutException() {
App.main(new String[]{}); assertDoesNotThrow(() -> App.main(new String[]{}));
} }
} }

View File

@ -25,13 +25,23 @@ package com.iluwatar.doublechecked.locking;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
/** /**
* Application test * Application test
*/ */
public class AppTest { class AppTest {
/**
* Issue: Add at least one assertion to this test case.
*
* Solution: Inserted assertion to check whether the execution of the main method in {@link App#main(String[])}
* throws an exception.
*/
@Test @Test
public void test() { void shouldExecuteApplicationWithoutException() {
App.main(new String[]{}); assertDoesNotThrow(() -> App.main(new String[]{}));
} }
} }

View File

@ -25,13 +25,23 @@ package com.iluwatar.doubledispatch;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
/** /**
* Application test * Application test
*/ */
public class AppTest { class AppTest {
/**
* Issue: Add at least one assertion to this test case.
*
* Solution: Inserted assertion to check whether the execution of the main method in {@link App#main(String[])}
* throws an exception.
*/
@Test @Test
public void test() { void shouldExecuteApplicationWithoutException() {
App.main(new String[]{}); assertDoesNotThrow(() -> App.main(new String[]{}));
} }
} }

View File

@ -25,13 +25,22 @@ package com.iluwatar.eip.aggregator;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
/** /**
* Test for App class * Test for App class
*/ */
public class AppTest { class AppTest {
/**
* Issue: Add at least one assertion to this test case.
*
* Solution: Inserted assertion to check whether the execution of the main method in {@link App#main(String[])}
* throws an exception.
*/
@Test @Test
public void testMain() throws Exception { void shouldExecuteApplicationWithoutException() {
App.main(new String[]{}); assertDoesNotThrow(() -> App.main(new String[]{}));
} }
} }

View File

@ -25,13 +25,22 @@ package com.iluwatar.eip.message.channel;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
/** /**
* Application test * Application test
*/ */
public class AppTest { class AppTest {
/**
* Issue: Add at least one assertion to this test case.
*
* Solution: Inserted assertion to check whether the execution of the main method in {@link App#main(String[])}
* throws an exception.
*/
@Test @Test
public void test() throws Exception { void shouldExecuteApplicationWithoutException() {
App.main(new String[]{}); assertDoesNotThrow(() -> App.main(new String[]{}));
} }
} }

View File

@ -25,13 +25,22 @@ package com.iluwatar.eip.publish.subscribe;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
/** /**
* Application test * Application test
*/ */
public class AppTest { class AppTest {
/**
* Issue: Add at least one assertion to this test case.
*
* Solution: Inserted assertion to check whether the execution of the main method in {@link App#main(String[])}
* throws an exception.
*/
@Test @Test
public void test() throws Exception { void shouldExecuteApplicationWithoutException() {
App.main(new String[]{}); assertDoesNotThrow(() -> App.main(new String[]{}));
} }
} }

View File

@ -25,13 +25,22 @@ package com.iluwatar.eip.splitter;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
/** /**
* Test for App class * Test for App class
*/ */
public class AppTest { class AppTest {
/**
* Issue: Add at least one assertion to this test case.
*
* Solution: Inserted assertion to check whether the execution of the main method in {@link App#main(String[])}
* throws an exception.
*/
@Test @Test
public void testMain() throws Exception { void shouldExecuteApplicationWithoutException() {
App.main(new String[]{}); assertDoesNotThrow(() -> App.main(new String[]{}));
} }
} }

View File

@ -25,13 +25,22 @@ package com.iluwatar.eip.wiretap;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
/** /**
* Test for App class * Test for App class
*/ */
public class AppTest { class AppTest {
/**
* Issue: Add at least one assertion to this test case.
*
* Solution: Inserted assertion to check whether the execution of the main method in {@link App#main(String[])}
* throws an exception.
*/
@Test @Test
public void testMain() throws Exception { void shouldExecuteApplicationWithoutException() {
App.main(new String[]{}); assertDoesNotThrow(() -> App.main(new String[]{}));
} }
} }

View File

@ -25,13 +25,22 @@ package com.iluwatar.event.aggregator;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
/** /**
* Application test * Application test
*/ */
public class AppTest { class AppTest {
/**
* Issue: Add at least one assertion to this test case.
*
* Solution: Inserted assertion to check whether the execution of the main method in {@link App#main(String[])}
* throws an exception.
*/
@Test @Test
public void test() { void shouldExecuteApplicationWithoutException() {
App.main(new String[]{}); assertDoesNotThrow(() -> App.main(new String[]{}));
} }
} }

View File

@ -25,12 +25,22 @@ package com.iluwatar.event.asynchronous;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
/** /**
* Tests that EventAsynchronous example runs without errors. * Tests that EventAsynchronous example runs without errors.
*/ */
public class AppTest { class AppTest {
/**
* Issue: Add at least one assertion to this test case.
*
* Solution: Inserted assertion to check whether the execution of the main method in {@link App#main(String[])}
* throws an exception.
*/
@Test @Test
public void test() { void shouldExecuteApplicationWithoutException() {
App.main(new String[]{}); assertDoesNotThrow(() -> App.main(new String[]{}));
} }
} }

View File

@ -25,12 +25,22 @@ package com.iluwatar.eda;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
/** /**
* Tests that Event Driven Architecture example runs without errors. * Tests that Event Driven Architecture example runs without errors.
*/ */
public class AppTest { class AppTest {
/**
* Issue: Add at least one assertion to this test case.
*
* Solution: Inserted assertion to check whether the execution of the main method in {@link App#main(String[])}
* throws an exception.
*/
@Test @Test
public void test() { void shouldExecuteApplicationWithoutException() {
App.main(new String[]{}); assertDoesNotThrow(() -> App.main(new String[]{}));
} }
} }

View File

@ -29,19 +29,21 @@ import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
/** /**
* Tests execute-around example. * Tests execute-around example.
*/ */
public class AppTest { class AppTest {
@Test @Test
public void test() throws IOException { void shouldExecuteApplicationWithoutException() {
App.main(new String[]{}); assertDoesNotThrow(() -> App.main(new String[]{}));
} }
@BeforeEach @BeforeEach
@AfterEach @AfterEach
public void cleanup() { void cleanup() {
var file = new File("testfile.txt"); var file = new File("testfile.txt");
file.delete(); file.delete();
} }

View File

@ -45,4 +45,8 @@ public class Commander implements CommanderExtension {
public void commanderReady() { public void commanderReady() {
LOGGER.info("[Commander] " + unit.getName() + " is ready!"); LOGGER.info("[Commander] " + unit.getName() + " is ready!");
} }
public CommanderUnit getUnit() {
return unit;
}
} }

View File

@ -43,6 +43,10 @@ public class Sergeant implements SergeantExtension {
@Override @Override
public void sergeantReady() { public void sergeantReady() {
LOGGER.info("[Sergeant] " + unit.getName() + " is ready! "); LOGGER.info("[Sergeant] " + unit.getName() + " is ready!");
}
public SergeantUnit getUnit() {
return unit;
} }
} }

View File

@ -44,4 +44,8 @@ public class Soldier implements SoldierExtension {
public void soldierReady() { public void soldierReady() {
LOGGER.info("[Solider] " + unit.getName() + " is ready!"); LOGGER.info("[Solider] " + unit.getName() + " is ready!");
} }
public SoldierUnit getUnit() {
return unit;
}
} }

View File

@ -23,13 +23,16 @@
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
/** /**
* Created by Srdjan on 03-May-17. * Created by Srdjan on 03-May-17.
*/ */
public class AppTest { class AppTest {
@Test @Test
public void main() { void shouldExecuteApplicationWithoutException() {
App.main(new String[]{}); assertDoesNotThrow(() -> App.main(new String[]{}));
} }
} }

View File

@ -23,17 +23,43 @@
package concreteextensions; package concreteextensions;
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.read.ListAppender;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.slf4j.LoggerFactory;
import units.CommanderUnit; import units.CommanderUnit;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
/** /**
* Created by Srdjan on 03-May-17. * Created by Srdjan on 03-May-17.
*
* Modified by ToxicDreamz on 15-Aug-20
*/ */
public class CommanderTest { class CommanderTest {
@Test @Test
public void commanderReady() { void shouldExecuteCommanderReady() {
Logger commanderLogger = (Logger) LoggerFactory.getLogger(Commander.class);
ListAppender<ILoggingEvent> listAppender = new ListAppender<>();
listAppender.start();
commanderLogger.addAppender(listAppender);
final var commander = new Commander(new CommanderUnit("CommanderUnitTest")); final var commander = new Commander(new CommanderUnit("CommanderUnitTest"));
commander.commanderReady(); commander.commanderReady();
List<ILoggingEvent> logsList = listAppender.list;
assertEquals("[Commander] " + commander.getUnit().getName() + " is ready!", logsList.get(0)
.getMessage());
assertEquals(Level.INFO, logsList.get(0)
.getLevel());
} }
} }

View File

@ -23,17 +23,41 @@
package concreteextensions; package concreteextensions;
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.read.ListAppender;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.slf4j.LoggerFactory;
import units.SergeantUnit; import units.SergeantUnit;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
/** /**
* Created by Srdjan on 03-May-17. * Created by Srdjan on 03-May-17.
*/ */
public class SergeantTest { class SergeantTest {
@Test @Test
public void sergeantReady() { void sergeantReady() {
Logger sergeantLogger = (Logger) LoggerFactory.getLogger(Sergeant.class);
ListAppender<ILoggingEvent> listAppender = new ListAppender<>();
listAppender.start();
sergeantLogger.addAppender(listAppender);
final var sergeant = new Sergeant(new SergeantUnit("SergeantUnitTest")); final var sergeant = new Sergeant(new SergeantUnit("SergeantUnitTest"));
sergeant.sergeantReady(); sergeant.sergeantReady();
List<ILoggingEvent> logsList = listAppender.list;
assertEquals("[Sergeant] " + sergeant.getUnit().getName() + " is ready!", logsList.get(0)
.getMessage());
assertEquals(Level.INFO, logsList.get(0)
.getLevel());
} }
} }

View File

@ -23,17 +23,41 @@
package concreteextensions; package concreteextensions;
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.read.ListAppender;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.slf4j.LoggerFactory;
import units.SoldierUnit; import units.SoldierUnit;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
/** /**
* Created by Srdjan on 03-May-17. * Created by Srdjan on 03-May-17.
*/ */
public class SoldierTest { class SoldierTest {
@Test @Test
public void soldierReady() { void soldierReady() {
Logger soldierLogger = (Logger) LoggerFactory.getLogger(Soldier.class);
ListAppender<ILoggingEvent> listAppender = new ListAppender<>();
listAppender.start();
soldierLogger.addAppender(listAppender);
final var soldier = new Soldier(new SoldierUnit("SoldierUnitTest")); final var soldier = new Soldier(new SoldierUnit("SoldierUnitTest"));
soldier.soldierReady(); soldier.soldierReady();
List<ILoggingEvent> logsList = listAppender.list;
assertEquals("[Soldier] " + soldier.getUnit().getName() + " is ready!", logsList.get(0)
.getMessage());
assertEquals(Level.INFO, logsList.get(0)
.getLevel());
} }
} }

View File

@ -25,13 +25,15 @@ package com.iluwatar.facade;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
/** /**
* Application test * Application test
*/ */
public class AppTest { class AppTest {
@Test @Test
public void test() { void shouldExecuteApplicationWithoutException() {
App.main(new String[]{}); assertDoesNotThrow(() -> App.main(new String[]{}));
} }
} }

View File

@ -26,14 +26,16 @@ package com.iluwatar.factorykit.app;
import com.iluwatar.factorykit.App; import com.iluwatar.factorykit.App;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
/** /**
* Application Test Entrypoint * Application Test Entrypoint
*/ */
public class AppTest { class AppTest {
@Test @Test
public void test() { void shouldExecuteApplicationWithoutException() {
App.main(new String[]{}); assertDoesNotThrow(() -> App.main(new String[]{}));
} }
} }

View File

@ -25,12 +25,15 @@ package com.iluwatar.factory.method;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
/** /**
* Tests that Factory Method example runs without errors. * Tests that Factory Method example runs without errors.
*/ */
public class AppTest { class AppTest {
@Test @Test
public void test() { void shouldExecuteWithoutException() {
App.main(new String[]{}); assertDoesNotThrow(() -> App.main(new String[]{}));
} }
} }

View File

@ -25,13 +25,15 @@ package com.iluwatar.fluentinterface.app;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
/** /**
* Application Test Entry * Application Test Entry
*/ */
public class AppTest { class AppTest {
@Test @Test
public void test() { void shouldExecuteWithoutException() {
App.main(new String[]{}); assertDoesNotThrow(() -> App.main(new String[]{}));
} }
} }

View File

@ -57,15 +57,10 @@ public final class Dispatcher {
*/ */
public void menuItemSelected(MenuItem menuItem) { public void menuItemSelected(MenuItem menuItem) {
dispatchAction(new MenuAction(menuItem)); dispatchAction(new MenuAction(menuItem));
switch (menuItem) { if (menuItem == MenuItem.COMPANY) {
case HOME: dispatchAction(new ContentAction(Content.COMPANY));
case PRODUCTS: } else {
default: dispatchAction(new ContentAction(Content.PRODUCTS));
dispatchAction(new ContentAction(Content.PRODUCTS));
break;
case COMPANY:
dispatchAction(new ContentAction(Content.COMPANY));
break;
} }
} }

View File

@ -25,13 +25,15 @@ package com.iluwatar.flux.app;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
/** /**
* Application test * Application test
*/ */
public class AppTest { class AppTest {
@Test @Test
public void test() { void shouldExecuteWithoutException() {
App.main(new String[]{}); assertDoesNotThrow(() -> App.main(new String[]{}));
} }
} }

View File

@ -25,13 +25,15 @@ package com.iluwatar.flyweight;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
/** /**
* Application test * Application test
*/ */
public class AppTest { class AppTest {
@Test @Test
public void test() { void shouldExecuteApplicationWithoutException() {
App.main(new String[]{}); assertDoesNotThrow(() -> App.main(new String[]{}));
} }
} }

View File

@ -25,13 +25,15 @@ package com.iluwatar.front.controller;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
/** /**
* Application test * Application test
*/ */
public class AppTest { class AppTest {
@Test @Test
public void test() { void shouldExecuteApplicationWithoutException() {
App.main(new String[]{}); assertDoesNotThrow(() -> App.main(new String[]{}));
} }
} }

View File

@ -39,6 +39,12 @@
<groupId>junit</groupId> <groupId>junit</groupId>
<artifactId>junit</artifactId> <artifactId>junit</artifactId>
</dependency> </dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<scope>test</scope>
</dependency>
</dependencies> </dependencies>
<build> <build>
<plugins> <plugins>

View File

@ -25,14 +25,16 @@ package com.iluwatar.gameloop;
import org.junit.Test; import org.junit.Test;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
/** /**
* App unit test class. * App unit test class.
*/ */
public class AppTest { public class AppTest {
@Test @Test
public void testMain() { public void shouldExecuteApplicationWithoutException() {
new App().main(new String[]{}); assertDoesNotThrow(() -> App.main(new String[]{}));
} }
} }

View File

@ -25,13 +25,15 @@ package com.iluwatar.halfsynchalfasync;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
/** /**
* Application test * Application test
*/ */
public class AppTest { class AppTest {
@Test @Test
public void test() { void shouldExecuteApplicationWithoutException() {
App.main(null); assertDoesNotThrow(() -> App.main(null));
} }
} }

View File

@ -46,6 +46,7 @@ public class MongoTicketRepository implements LotteryTicketRepository {
private static final String DEFAULT_DB = "lotteryDB"; private static final String DEFAULT_DB = "lotteryDB";
private static final String DEFAULT_TICKETS_COLLECTION = "lotteryTickets"; private static final String DEFAULT_TICKETS_COLLECTION = "lotteryTickets";
private static final String DEFAULT_COUNTERS_COLLECTION = "counters"; private static final String DEFAULT_COUNTERS_COLLECTION = "counters";
private static final String TICKET_ID = "ticketId";
private MongoClient mongoClient; private MongoClient mongoClient;
private MongoDatabase database; private MongoDatabase database;
@ -93,7 +94,7 @@ public class MongoTicketRepository implements LotteryTicketRepository {
} }
private void initCounters() { private void initCounters() {
var doc = new Document("_id", "ticketId").append("seq", 1); var doc = new Document("_id", TICKET_ID).append("seq", 1);
countersCollection.insertOne(doc); countersCollection.insertOne(doc);
} }
@ -103,7 +104,7 @@ public class MongoTicketRepository implements LotteryTicketRepository {
* @return next ticket id * @return next ticket id
*/ */
public int getNextId() { public int getNextId() {
var find = new Document("_id", "ticketId"); var find = new Document("_id", TICKET_ID);
var increase = new Document("seq", 1); var increase = new Document("seq", 1);
var update = new Document("$inc", increase); var update = new Document("$inc", increase);
var result = countersCollection.findOneAndUpdate(find, update); var result = countersCollection.findOneAndUpdate(find, update);
@ -131,7 +132,7 @@ public class MongoTicketRepository implements LotteryTicketRepository {
@Override @Override
public Optional<LotteryTicket> findById(LotteryTicketId id) { public Optional<LotteryTicket> findById(LotteryTicketId id) {
return ticketsCollection return ticketsCollection
.find(new Document("ticketId", id.getId())) .find(new Document(TICKET_ID, id.getId()))
.limit(1) .limit(1)
.into(new ArrayList<>()) .into(new ArrayList<>())
.stream() .stream()
@ -142,7 +143,7 @@ public class MongoTicketRepository implements LotteryTicketRepository {
@Override @Override
public Optional<LotteryTicketId> save(LotteryTicket ticket) { public Optional<LotteryTicketId> save(LotteryTicket ticket) {
var ticketId = getNextId(); var ticketId = getNextId();
var doc = new Document("ticketId", ticketId); var doc = new Document(TICKET_ID, ticketId);
doc.put("email", ticket.getPlayerDetails().getEmail()); doc.put("email", ticket.getPlayerDetails().getEmail());
doc.put("bank", ticket.getPlayerDetails().getBankAccount()); doc.put("bank", ticket.getPlayerDetails().getBankAccount());
doc.put("phone", ticket.getPlayerDetails().getPhoneNumber()); doc.put("phone", ticket.getPlayerDetails().getPhoneNumber());
@ -173,7 +174,7 @@ public class MongoTicketRepository implements LotteryTicketRepository {
.map(Integer::parseInt) .map(Integer::parseInt)
.collect(Collectors.toSet()); .collect(Collectors.toSet());
var lotteryNumbers = LotteryNumbers.create(numbers); var lotteryNumbers = LotteryNumbers.create(numbers);
var ticketId = new LotteryTicketId(doc.getInteger("ticketId")); var ticketId = new LotteryTicketId(doc.getInteger(TICKET_ID));
return new LotteryTicket(ticketId, playerDetails, lotteryNumbers); return new LotteryTicket(ticketId, playerDetails, lotteryNumbers);
} }
} }

View File

@ -36,6 +36,9 @@ public class MongoEventLog implements LotteryEventLog {
private static final String DEFAULT_DB = "lotteryDB"; private static final String DEFAULT_DB = "lotteryDB";
private static final String DEFAULT_EVENTS_COLLECTION = "events"; private static final String DEFAULT_EVENTS_COLLECTION = "events";
private static final String EMAIL = "email";
private static final String PHONE = "phone";
public static final String MESSAGE = "message";
private MongoClient mongoClient; private MongoClient mongoClient;
private MongoDatabase database; private MongoDatabase database;
@ -107,41 +110,41 @@ public class MongoEventLog implements LotteryEventLog {
@Override @Override
public void ticketSubmitted(PlayerDetails details) { public void ticketSubmitted(PlayerDetails details) {
var document = new Document("email", details.getEmail()); var document = new Document(EMAIL, details.getEmail());
document.put("phone", details.getPhoneNumber()); document.put(PHONE, details.getPhoneNumber());
document.put("bank", details.getBankAccount()); document.put("bank", details.getBankAccount());
document document
.put("message", "Lottery ticket was submitted and bank account was charged for 3 credits."); .put(MESSAGE, "Lottery ticket was submitted and bank account was charged for 3 credits.");
eventsCollection.insertOne(document); eventsCollection.insertOne(document);
stdOutEventLog.ticketSubmitted(details); stdOutEventLog.ticketSubmitted(details);
} }
@Override @Override
public void ticketSubmitError(PlayerDetails details) { public void ticketSubmitError(PlayerDetails details) {
var document = new Document("email", details.getEmail()); var document = new Document(EMAIL, details.getEmail());
document.put("phone", details.getPhoneNumber()); document.put(PHONE, details.getPhoneNumber());
document.put("bank", details.getBankAccount()); document.put("bank", details.getBankAccount());
document.put("message", "Lottery ticket could not be submitted because lack of funds."); document.put(MESSAGE, "Lottery ticket could not be submitted because lack of funds.");
eventsCollection.insertOne(document); eventsCollection.insertOne(document);
stdOutEventLog.ticketSubmitError(details); stdOutEventLog.ticketSubmitError(details);
} }
@Override @Override
public void ticketDidNotWin(PlayerDetails details) { public void ticketDidNotWin(PlayerDetails details) {
var document = new Document("email", details.getEmail()); var document = new Document(EMAIL, details.getEmail());
document.put("phone", details.getPhoneNumber()); document.put(PHONE, details.getPhoneNumber());
document.put("bank", details.getBankAccount()); document.put("bank", details.getBankAccount());
document.put("message", "Lottery ticket was checked and unfortunately did not win this time."); document.put(MESSAGE, "Lottery ticket was checked and unfortunately did not win this time.");
eventsCollection.insertOne(document); eventsCollection.insertOne(document);
stdOutEventLog.ticketDidNotWin(details); stdOutEventLog.ticketDidNotWin(details);
} }
@Override @Override
public void ticketWon(PlayerDetails details, int prizeAmount) { public void ticketWon(PlayerDetails details, int prizeAmount) {
var document = new Document("email", details.getEmail()); var document = new Document(EMAIL, details.getEmail());
document.put("phone", details.getPhoneNumber()); document.put(PHONE, details.getPhoneNumber());
document.put("bank", details.getBankAccount()); document.put("bank", details.getBankAccount());
document.put("message", String document.put(MESSAGE, String
.format("Lottery ticket won! The bank account was deposited with %d credits.", .format("Lottery ticket won! The bank account was deposited with %d credits.",
prizeAmount)); prizeAmount));
eventsCollection.insertOne(document); eventsCollection.insertOne(document);
@ -150,10 +153,10 @@ public class MongoEventLog implements LotteryEventLog {
@Override @Override
public void prizeError(PlayerDetails details, int prizeAmount) { public void prizeError(PlayerDetails details, int prizeAmount) {
var document = new Document("email", details.getEmail()); var document = new Document(EMAIL, details.getEmail());
document.put("phone", details.getPhoneNumber()); document.put(PHONE, details.getPhoneNumber());
document.put("bank", details.getBankAccount()); document.put("bank", details.getBankAccount());
document.put("message", String document.put(MESSAGE, String
.format("Lottery ticket won! Unfortunately the bank credit transfer of %d failed.", .format("Lottery ticket won! Unfortunately the bank credit transfer of %d failed.",
prizeAmount)); prizeAmount));
eventsCollection.insertOne(document); eventsCollection.insertOne(document);

View File

@ -25,13 +25,16 @@ package com.iluwatar.hexagonal;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
/** /**
* Unit test for simple App. * Unit test for simple App.
*/ */
class AppTest { class AppTest {
@Test @Test
void testApp() { void shouldExecuteApplicationWithoutException() {
App.main(new String[]{}); assertDoesNotThrow(() -> App.main(new String[]{}));
} }
} }

View File

@ -25,13 +25,15 @@ package com.iluwatar.intercepting.filter;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
/** /**
* Application test. * Application test.
*/ */
public class AppTest { class AppTest {
@Test @Test
public void test() { void shouldExecuteApplicationWithoutException() {
App.main(new String[]{}); assertDoesNotThrow(() -> App.main(new String[]{}));
} }
} }

View File

@ -25,13 +25,15 @@ package com.iluwatar.interpreter;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
/** /**
* Application test * Application test
*/ */
public class AppTest { class AppTest {
@Test @Test
public void test() { void shouldExecuteApplicationWithoutException() {
App.main(new String[]{}); assertDoesNotThrow(() -> App.main(new String[]{}));
} }
} }

View File

@ -25,13 +25,15 @@ package com.iluwatar.iterator;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
/** /**
* Application Test * Application Test
*/ */
class AppTest { class AppTest {
@Test @Test
void testApp() { void shouldExecuteApplicationWithoutException() {
App.main(new String[]{}); assertDoesNotThrow(() -> App.main(new String[]{}));
} }
} }

View File

@ -81,6 +81,7 @@ import java.util.List;
public class App { public class App {
private static final CakeBakingService cakeBakingService = new CakeBakingServiceImpl(); private static final CakeBakingService cakeBakingService = new CakeBakingServiceImpl();
public static final String STRAWBERRY = "strawberry";
/** /**
* Application entry point. * Application entry point.
@ -103,10 +104,10 @@ public class App {
private static void initializeData(CakeBakingService cakeBakingService) { private static void initializeData(CakeBakingService cakeBakingService) {
cakeBakingService.saveNewLayer(new CakeLayerInfo("chocolate", 1200)); cakeBakingService.saveNewLayer(new CakeLayerInfo("chocolate", 1200));
cakeBakingService.saveNewLayer(new CakeLayerInfo("banana", 900)); cakeBakingService.saveNewLayer(new CakeLayerInfo("banana", 900));
cakeBakingService.saveNewLayer(new CakeLayerInfo("strawberry", 950)); cakeBakingService.saveNewLayer(new CakeLayerInfo(STRAWBERRY, 950));
cakeBakingService.saveNewLayer(new CakeLayerInfo("lemon", 950)); cakeBakingService.saveNewLayer(new CakeLayerInfo("lemon", 950));
cakeBakingService.saveNewLayer(new CakeLayerInfo("vanilla", 950)); cakeBakingService.saveNewLayer(new CakeLayerInfo("vanilla", 950));
cakeBakingService.saveNewLayer(new CakeLayerInfo("strawberry", 950)); cakeBakingService.saveNewLayer(new CakeLayerInfo(STRAWBERRY, 950));
cakeBakingService.saveNewTopping(new CakeToppingInfo("candies", 350)); cakeBakingService.saveNewTopping(new CakeToppingInfo("candies", 350));
cakeBakingService.saveNewTopping(new CakeToppingInfo("cherry", 350)); cakeBakingService.saveNewTopping(new CakeToppingInfo("cherry", 350));
@ -114,7 +115,7 @@ public class App {
var cake1 = new CakeInfo(new CakeToppingInfo("candies", 0), List.of( var cake1 = new CakeInfo(new CakeToppingInfo("candies", 0), List.of(
new CakeLayerInfo("chocolate", 0), new CakeLayerInfo("chocolate", 0),
new CakeLayerInfo("banana", 0), new CakeLayerInfo("banana", 0),
new CakeLayerInfo("strawberry", 0))); new CakeLayerInfo(STRAWBERRY, 0)));
try { try {
cakeBakingService.bakeNewCake(cake1); cakeBakingService.bakeNewCake(cake1);
} catch (CakeBakingException e) { } catch (CakeBakingException e) {
@ -123,7 +124,7 @@ public class App {
var cake2 = new CakeInfo(new CakeToppingInfo("cherry", 0), List.of( var cake2 = new CakeInfo(new CakeToppingInfo("cherry", 0), List.of(
new CakeLayerInfo("vanilla", 0), new CakeLayerInfo("vanilla", 0),
new CakeLayerInfo("lemon", 0), new CakeLayerInfo("lemon", 0),
new CakeLayerInfo("strawberry", 0))); new CakeLayerInfo(STRAWBERRY, 0)));
try { try {
cakeBakingService.bakeNewCake(cake2); cakeBakingService.bakeNewCake(cake2);
} catch (CakeBakingException e) { } catch (CakeBakingException e) {

View File

@ -23,19 +23,19 @@
package com.iluwatar.layers.app; package com.iluwatar.layers.app;
import com.iluwatar.layers.app.App;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
/** /**
* *
* Application test * Application test
* *
*/ */
public class AppTest { class AppTest {
@Test @Test
public void test() { void shouldExecuteApplicationWithoutException() {
String[] args = {}; assertDoesNotThrow(() -> App.main(new String[]{}));
App.main(args);
} }
} }

View File

@ -25,16 +25,17 @@ package com.iluwatar.lazy.loading;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
/** /**
* *
* Application test * Application test
* *
*/ */
public class AppTest { class AppTest {
@Test @Test
public void test() { void shouldExecuteApplicationWithoutException() {
String[] args = {}; assertDoesNotThrow(() -> App.main(new String[]{}));
App.main(args);
} }
} }

View File

@ -36,6 +36,7 @@ public abstract class AbstractInstance implements Instance, Runnable {
private static final Logger LOGGER = LoggerFactory.getLogger(AbstractInstance.class); private static final Logger LOGGER = LoggerFactory.getLogger(AbstractInstance.class);
protected static final int HEARTBEAT_INTERVAL = 5000; protected static final int HEARTBEAT_INTERVAL = 5000;
private static final String INSTANCE = "Instance ";
protected MessageManager messageManager; protected MessageManager messageManager;
protected Queue<Message> messageQueue; protected Queue<Message> messageQueue;
@ -106,27 +107,27 @@ public abstract class AbstractInstance implements Instance, Runnable {
private void processMessage(Message message) { private void processMessage(Message message) {
switch (message.getType()) { switch (message.getType()) {
case ELECTION: case ELECTION:
LOGGER.info("Instance " + localId + " - Election Message handling..."); LOGGER.info(INSTANCE + localId + " - Election Message handling...");
handleElectionMessage(message); handleElectionMessage(message);
break; break;
case LEADER: case LEADER:
LOGGER.info("Instance " + localId + " - Leader Message handling..."); LOGGER.info(INSTANCE + localId + " - Leader Message handling...");
handleLeaderMessage(message); handleLeaderMessage(message);
break; break;
case HEARTBEAT: case HEARTBEAT:
LOGGER.info("Instance " + localId + " - Heartbeat Message handling..."); LOGGER.info(INSTANCE + localId + " - Heartbeat Message handling...");
handleHeartbeatMessage(message); handleHeartbeatMessage(message);
break; break;
case ELECTION_INVOKE: case ELECTION_INVOKE:
LOGGER.info("Instance " + localId + " - Election Invoke Message handling..."); LOGGER.info(INSTANCE + localId + " - Election Invoke Message handling...");
handleElectionInvokeMessage(); handleElectionInvokeMessage();
break; break;
case LEADER_INVOKE: case LEADER_INVOKE:
LOGGER.info("Instance " + localId + " - Leader Invoke Message handling..."); LOGGER.info(INSTANCE + localId + " - Leader Invoke Message handling...");
handleLeaderInvokeMessage(); handleLeaderInvokeMessage();
break; break;
case HEARTBEAT_INVOKE: case HEARTBEAT_INVOKE:
LOGGER.info("Instance " + localId + " - Heartbeat Invoke Message handling..."); LOGGER.info(INSTANCE + localId + " - Heartbeat Invoke Message handling...");
handleHeartbeatInvokeMessage(); handleHeartbeatInvokeMessage();
break; break;
default: default:

View File

@ -41,6 +41,7 @@ import org.slf4j.LoggerFactory;
public class BullyInstance extends AbstractInstance { public class BullyInstance extends AbstractInstance {
private static final Logger LOGGER = LoggerFactory.getLogger(BullyInstance.class); private static final Logger LOGGER = LoggerFactory.getLogger(BullyInstance.class);
private static final String INSTANCE = "Instance ";
/** /**
* Constructor of BullyInstance. * Constructor of BullyInstance.
@ -59,20 +60,20 @@ public class BullyInstance extends AbstractInstance {
try { try {
boolean isLeaderAlive = messageManager.sendHeartbeatMessage(leaderId); boolean isLeaderAlive = messageManager.sendHeartbeatMessage(leaderId);
if (isLeaderAlive) { if (isLeaderAlive) {
LOGGER.info("Instance " + localId + "- Leader is alive."); LOGGER.info(INSTANCE + localId + "- Leader is alive.");
Thread.sleep(HEARTBEAT_INTERVAL); Thread.sleep(HEARTBEAT_INTERVAL);
messageManager.sendHeartbeatInvokeMessage(localId); messageManager.sendHeartbeatInvokeMessage(localId);
} else { } else {
LOGGER.info("Instance " + localId + "- Leader is not alive. Start election."); LOGGER.info(INSTANCE + localId + "- Leader is not alive. Start election.");
boolean electionResult = boolean electionResult =
messageManager.sendElectionMessage(localId, String.valueOf(localId)); messageManager.sendElectionMessage(localId, String.valueOf(localId));
if (electionResult) { if (electionResult) {
LOGGER.info("Instance " + localId + "- Succeed in election. Start leader notification."); LOGGER.info(INSTANCE + localId + "- Succeed in election. Start leader notification.");
messageManager.sendLeaderMessage(localId, localId); messageManager.sendLeaderMessage(localId, localId);
} }
} }
} catch (InterruptedException e) { } catch (InterruptedException e) {
LOGGER.info("Instance " + localId + "- Interrupted."); LOGGER.info(INSTANCE + localId + "- Interrupted.");
} }
} }
@ -84,10 +85,10 @@ public class BullyInstance extends AbstractInstance {
@Override @Override
protected void handleElectionInvokeMessage() { protected void handleElectionInvokeMessage() {
if (!isLeader()) { if (!isLeader()) {
LOGGER.info("Instance " + localId + "- Start election."); LOGGER.info(INSTANCE + localId + "- Start election.");
boolean electionResult = messageManager.sendElectionMessage(localId, String.valueOf(localId)); boolean electionResult = messageManager.sendElectionMessage(localId, String.valueOf(localId));
if (electionResult) { if (electionResult) {
LOGGER.info("Instance " + localId + "- Succeed in election. Start leader notification."); LOGGER.info(INSTANCE + localId + "- Succeed in election. Start leader notification.");
leaderId = localId; leaderId = localId;
messageManager.sendLeaderMessage(localId, localId); messageManager.sendLeaderMessage(localId, localId);
messageManager.sendHeartbeatInvokeMessage(localId); messageManager.sendHeartbeatInvokeMessage(localId);
@ -101,25 +102,25 @@ public class BullyInstance extends AbstractInstance {
@Override @Override
protected void handleLeaderMessage(Message message) { protected void handleLeaderMessage(Message message) {
leaderId = Integer.valueOf(message.getContent()); leaderId = Integer.valueOf(message.getContent());
LOGGER.info("Instance " + localId + " - Leader update done."); LOGGER.info(INSTANCE + localId + " - Leader update done.");
} }
private boolean isLeader() { private boolean isLeader() {
return localId == leaderId; return localId == leaderId;
} }
/**
* Not used in Bully instance.
*/
@Override @Override
protected void handleLeaderInvokeMessage() { protected void handleLeaderInvokeMessage() {
// Not used in Bully Instance
} }
@Override @Override
protected void handleHeartbeatMessage(Message message) { protected void handleHeartbeatMessage(Message message) {
// Not used in Bully Instance
} }
@Override @Override
protected void handleElectionMessage(Message message) { protected void handleElectionMessage(Message message) {
// Not used in Bully Instance
} }
} }

View File

@ -46,6 +46,7 @@ import org.slf4j.LoggerFactory;
public class RingInstance extends AbstractInstance { public class RingInstance extends AbstractInstance {
private static final Logger LOGGER = LoggerFactory.getLogger(RingInstance.class); private static final Logger LOGGER = LoggerFactory.getLogger(RingInstance.class);
private static final String INSTANCE = "Instance ";
/** /**
* Constructor of RingInstance. * Constructor of RingInstance.
@ -64,15 +65,15 @@ public class RingInstance extends AbstractInstance {
try { try {
var isLeaderAlive = messageManager.sendHeartbeatMessage(this.leaderId); var isLeaderAlive = messageManager.sendHeartbeatMessage(this.leaderId);
if (isLeaderAlive) { if (isLeaderAlive) {
LOGGER.info("Instance " + localId + "- Leader is alive. Start next heartbeat in 5 second."); LOGGER.info(INSTANCE + localId + "- Leader is alive. Start next heartbeat in 5 second.");
Thread.sleep(HEARTBEAT_INTERVAL); Thread.sleep(HEARTBEAT_INTERVAL);
messageManager.sendHeartbeatInvokeMessage(this.localId); messageManager.sendHeartbeatInvokeMessage(this.localId);
} else { } else {
LOGGER.info("Instance " + localId + "- Leader is not alive. Start election."); LOGGER.info(INSTANCE + localId + "- Leader is not alive. Start election.");
messageManager.sendElectionMessage(this.localId, String.valueOf(this.localId)); messageManager.sendElectionMessage(this.localId, String.valueOf(this.localId));
} }
} catch (InterruptedException e) { } catch (InterruptedException e) {
LOGGER.info("Instance " + localId + "- Interrupted."); LOGGER.info(INSTANCE + localId + "- Interrupted.");
} }
} }
@ -85,14 +86,14 @@ public class RingInstance extends AbstractInstance {
@Override @Override
protected void handleElectionMessage(Message message) { protected void handleElectionMessage(Message message) {
var content = message.getContent(); var content = message.getContent();
LOGGER.info("Instance " + localId + " - Election Message: " + content); LOGGER.info(INSTANCE + localId + " - Election Message: " + content);
var candidateList = Arrays.stream(content.trim().split(",")) var candidateList = Arrays.stream(content.trim().split(","))
.map(Integer::valueOf) .map(Integer::valueOf)
.sorted() .sorted()
.collect(Collectors.toList()); .collect(Collectors.toList());
if (candidateList.contains(localId)) { if (candidateList.contains(localId)) {
var newLeaderId = candidateList.get(0); var newLeaderId = candidateList.get(0);
LOGGER.info("Instance " + localId + " - New leader should be " + newLeaderId + "."); LOGGER.info(INSTANCE + localId + " - New leader should be " + newLeaderId + ".");
messageManager.sendLeaderMessage(localId, newLeaderId); messageManager.sendLeaderMessage(localId, newLeaderId);
} else { } else {
content += "," + localId; content += "," + localId;
@ -108,11 +109,11 @@ public class RingInstance extends AbstractInstance {
protected void handleLeaderMessage(Message message) { protected void handleLeaderMessage(Message message) {
var newLeaderId = Integer.valueOf(message.getContent()); var newLeaderId = Integer.valueOf(message.getContent());
if (this.leaderId != newLeaderId) { if (this.leaderId != newLeaderId) {
LOGGER.info("Instance " + localId + " - Update leaderID"); LOGGER.info(INSTANCE + localId + " - Update leaderID");
this.leaderId = newLeaderId; this.leaderId = newLeaderId;
messageManager.sendLeaderMessage(localId, newLeaderId); messageManager.sendLeaderMessage(localId, newLeaderId);
} else { } else {
LOGGER.info("Instance " + localId + " - Leader update done. Start heartbeat."); LOGGER.info(INSTANCE + localId + " - Leader update done. Start heartbeat.");
messageManager.sendHeartbeatInvokeMessage(localId); messageManager.sendHeartbeatInvokeMessage(localId);
} }
} }
@ -122,14 +123,17 @@ public class RingInstance extends AbstractInstance {
*/ */
@Override @Override
protected void handleLeaderInvokeMessage() { protected void handleLeaderInvokeMessage() {
// Not used in Ring instance.
} }
@Override @Override
protected void handleHeartbeatMessage(Message message) { protected void handleHeartbeatMessage(Message message) {
// Not used in Ring instance.
} }
@Override @Override
protected void handleElectionInvokeMessage() { protected void handleElectionInvokeMessage() {
// Not used in Ring instance.
} }
} }

View File

@ -25,15 +25,16 @@ package com.iluwatar.leaderelection.bully;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
/** /**
* BullyApp unit test. * BullyApp unit test.
*/ */
public class BullyAppTest { class BullyAppTest {
@Test @Test
public void test() { void shouldExecuteApplicationWithoutException() {
String[] args = {}; assertDoesNotThrow(() -> BullyApp.main(new String[]{}));
BullyApp.main(args);
} }
} }

View File

@ -25,15 +25,16 @@ package com.iluwatar.leaderelection.ring;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
/** /**
* RingApp unit test. * RingApp unit test.
*/ */
public class RingAppTest { class RingAppTest {
@Test @Test
public void test() { void shouldExecuteApplicationWithoutException() {
String[] args = {}; assertDoesNotThrow(() -> RingApp.main(new String[]{}));
RingApp.main(args);
} }
} }

View File

@ -37,6 +37,11 @@
<artifactId>junit</artifactId> <artifactId>junit</artifactId>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<scope>test</scope>
</dependency>
<dependency> <dependency>
<groupId>org.mockito</groupId> <groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId> <artifactId>mockito-core</artifactId>

View File

@ -21,10 +21,13 @@
* THE SOFTWARE. * THE SOFTWARE.
*/ */
package com.iluwatar.leaderfollowers; package com;
import com.iluwatar.leaderfollowers.App;
import org.junit.Test; import org.junit.Test;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
/** /**
* *
* Application test * Application test
@ -33,9 +36,8 @@ import org.junit.Test;
public class AppTest { public class AppTest {
@Test @Test
public void test() throws InterruptedException { public void shouldExecuteApplicationWithoutException() {
String[] args = {}; assertDoesNotThrow(() -> App.main(new String[]{}));
App.main(args);
} }
} }

View File

@ -21,8 +21,10 @@
* THE SOFTWARE. * THE SOFTWARE.
*/ */
package com.iluwatar.leaderfollowers; package com;
import com.iluwatar.leaderfollowers.Task;
import com.iluwatar.leaderfollowers.TaskHandler;
import org.junit.Assert; import org.junit.Assert;
import org.junit.Test; import org.junit.Test;

View File

@ -21,8 +21,10 @@
* THE SOFTWARE. * THE SOFTWARE.
*/ */
package com.iluwatar.leaderfollowers; package com;
import com.iluwatar.leaderfollowers.Task;
import com.iluwatar.leaderfollowers.TaskSet;
import org.junit.Assert; import org.junit.Assert;
import org.junit.Test; import org.junit.Test;

View File

@ -21,8 +21,11 @@
* THE SOFTWARE. * THE SOFTWARE.
*/ */
package com.iluwatar.leaderfollowers; package com;
import com.iluwatar.leaderfollowers.TaskHandler;
import com.iluwatar.leaderfollowers.TaskSet;
import com.iluwatar.leaderfollowers.WorkCenter;
import org.junit.Assert; import org.junit.Assert;
import org.junit.Test; import org.junit.Test;

View File

@ -23,13 +23,15 @@
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
/** /**
* Application test * Application test
*/ */
public class AppTest { class AppTest {
@Test @Test
public void test() { void shouldExecuteApplicationWithoutException() {
App.main(new String[]{}); assertDoesNotThrow(() -> App.main(new String[]{}));
} }
} }

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