Add oving 6

This commit is contained in:
Andreas Omholt Olsen
2026-02-23 12:10:01 +01:00
parent 1a6645482b
commit 57adabe5be
23 changed files with 1419 additions and 0 deletions

View File

@@ -0,0 +1,160 @@
package oving6.highscorelist;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.List;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
public class HighscoreListTest {
private int pos1;
private int pos2;
private HighscoreList highscoreList;
private static void checkHighscoreList(String contextMessage, HighscoreList list,
List<Integer> elements) {
assertEquals(elements.size(), list.size(),
contextMessage + " -> Testing the length of the highscore list");
int i = 0;
for (int element : elements) {
assertEquals(element, list.getElement(i),
contextMessage + " -> Testing that the element at position " + i + " matches");
i++;
}
}
private void addResultWithListener(int pos, int element) {
pos1 = pos;
highscoreList.addResult(element);
// Check that the position that was changed is the same as the one sent to the listener
assertEquals(pos1, pos2, "Added " + element + " at position " + pos
+ " -> Testing the position received by the listener");
}
@BeforeEach
public void setUp() {
highscoreList = new HighscoreList(3);
pos1 = -1;
pos2 = -1;
}
@Test
@DisplayName("Test constructor")
public void testConstructor() {
assertEquals(0, highscoreList.size(), "Testing initialization of the highscore list");
}
@Test
@DisplayName("Add results (simple)")
public void testAddElementSimple() {
highscoreList.addResult(5);
HighscoreListTest.checkHighscoreList("Added 5 to an empty list", highscoreList, List.of(5));
highscoreList.addResult(6);
HighscoreListTest.checkHighscoreList("Added 6 to the list [5]", highscoreList,
List.of(5, 6));
highscoreList.addResult(2);
HighscoreListTest.checkHighscoreList("Added 2 to the list [5, 6]", highscoreList,
List.of(2, 5, 6));
}
@Test
@DisplayName("Add results - list becomes too long")
public void testAddElementMoreThanMax() {
highscoreList.addResult(5);
highscoreList.addResult(6);
highscoreList.addResult(2);
HighscoreListTest.checkHighscoreList("Added 5, 6, and 2 to the list", highscoreList,
List.of(2, 5, 6));
highscoreList.addResult(3);
HighscoreListTest.checkHighscoreList("Added 3 to the list [2, 5, 6]", highscoreList,
List.of(2, 3, 5));
highscoreList.addResult(7);
HighscoreListTest.checkHighscoreList("Added 7 to the list [2, 3, 5]", highscoreList,
List.of(2, 3, 5));
}
@Test
@DisplayName("Add two identical elements")
public void testAddElementDuplicate() {
highscoreList.addResult(5);
highscoreList.addResult(6);
highscoreList.addResult(2);
HighscoreListTest.checkHighscoreList("Added 5, 6, and 2 to the list", highscoreList,
List.of(2, 5, 6));
highscoreList.addResult(2);
HighscoreListTest.checkHighscoreList("Added 2 to the list [2, 5, 6]", highscoreList,
List.of(2, 2, 5));
}
@Test
@DisplayName("Test listeners (simple)")
public void testListListenersSimple() {
// Mock a listener
HighscoreListListener listener = (list, pos) -> pos2 = pos;
highscoreList.addHighscoreListListener(listener);
this.addResultWithListener(0, 5);
HighscoreListTest.checkHighscoreList("Added 5 to the list []", highscoreList, List.of(5));
this.addResultWithListener(1, 6);
HighscoreListTest.checkHighscoreList("Added 6 to the list [5]", highscoreList,
List.of(5, 6));
this.addResultWithListener(0, 2);
HighscoreListTest.checkHighscoreList("Added 2 to the list [5, 6]", highscoreList,
List.of(2, 5, 6));
}
@Test
@DisplayName("With listener - list becomes too long")
public void testListListenerMoreThanMax() {
// Mock a listener
HighscoreListListener listener = (list, pos) -> pos2 = pos;
highscoreList.addHighscoreListListener(listener);
highscoreList.addResult(5);
highscoreList.addResult(6);
highscoreList.addResult(2);
HighscoreListTest.checkHighscoreList("Added 5, 6, and 2 to the list", highscoreList,
List.of(2, 5, 6));
this.addResultWithListener(1, 3);
HighscoreListTest.checkHighscoreList("Added 3 to the list [2, 5, 6]", highscoreList,
List.of(2, 3, 5));
// Reset pos2 since the next element falls outside the list and is therefore not updated by
// itself and sent to the listener
pos2 = -1;
this.addResultWithListener(-1, 7);
HighscoreListTest.checkHighscoreList("Added 7 to the list [2, 3, 5]", highscoreList,
List.of(2, 3, 5));
}
@Test
@DisplayName("With listener - two identical elements")
public void testListListenerDuplicate() {
// Mock a listener
HighscoreListListener listener = (list, pos) -> pos2 = pos;
highscoreList.addHighscoreListListener(listener);
highscoreList.addResult(5);
highscoreList.addResult(6);
highscoreList.addResult(2);
HighscoreListTest.checkHighscoreList("Added 5, 6, and 2 to the list", highscoreList,
List.of(2, 5, 6));
this.addResultWithListener(1, 2);
HighscoreListTest.checkHighscoreList("Added 2 to the list [2, 5, 6]", highscoreList,
List.of(2, 2, 5));
}
}

View File

@@ -0,0 +1,100 @@
package oving6.logger;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.io.ByteArrayOutputStream;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
public class DistributingLoggerTest {
private static final String formatString = "%s: %s (%s)";
private ByteArrayOutputStream infoStream;
private ByteArrayOutputStream warnStream;
private ByteArrayOutputStream errorStream;
private DistributingLogger logger;
private StreamLogger infoLogger;
private StreamLogger warnLogger;
private StreamLogger errorLogger;
@BeforeEach
public void setUp() {
infoStream = new ByteArrayOutputStream();
warnStream = new ByteArrayOutputStream();
errorStream = new ByteArrayOutputStream();
infoLogger = new StreamLogger(infoStream);
warnLogger = new StreamLogger(warnStream);
errorLogger = new StreamLogger(errorStream);
logger = new DistributingLogger(errorLogger, warnLogger, infoLogger);
}
@Test
@DisplayName("Log to INFO")
public void testLogToInfo() {
infoLogger.setFormatString(formatString);
logger.log(ILogger.INFO, "Dette er en info-melding.", null);
assertEquals(String.format(formatString, ILogger.INFO, "Dette er en info-melding.", null),
infoStream.toString().trim(), "Test the format of the info message after logging");
assertEquals("", warnStream.toString(),
"Test the warning stream after logging an info message");
assertEquals("", errorStream.toString(),
"Test the error stream after logging an info message");
}
@Test
@DisplayName("Log to WARNING")
public void testLogToWarn() {
warnLogger.setFormatString(formatString);
logger.log(ILogger.WARNING, "Dette er en advarsel.", null);
assertEquals(String.format(formatString, ILogger.WARNING, "Dette er en advarsel.", null),
warnStream.toString().trim(),
"Test the format of the warning message after logging");
assertEquals("", infoStream.toString(),
"Test the info stream after logging a warning message");
assertEquals("", errorStream.toString(),
"Test the error stream after logging a warning message");
}
@Test
@DisplayName("Log to ERROR")
public void testLogToError() {
Exception exception = new IllegalStateException();
errorLogger.setFormatString(formatString);
logger.log(ILogger.ERROR, "Dette er en feilmelding.", exception);
assertEquals(
String.format(formatString, ILogger.ERROR, "Dette er en feilmelding.", exception),
errorStream.toString().trim(),
"Test the format of the error message after logging");
assertEquals("", warnStream.toString(),
"Test the warning stream after logging an error message");
assertEquals("", infoStream.toString(),
"Test the info stream after logging an error message");
}
@Test
@DisplayName("Change info logger")
public void testChangeInfoLogger() {
ByteArrayOutputStream newInfoStream = new ByteArrayOutputStream();
StreamLogger newInfoLogger = new StreamLogger(newInfoStream);
infoLogger.setFormatString(formatString);
logger.log(ILogger.INFO, "Dette er en info-melding.", null);
assertEquals(String.format(formatString, ILogger.INFO, "Dette er en info-melding.", null),
infoStream.toString().trim(), "Test the format of the info message after logging");
newInfoLogger.setFormatString(formatString);
logger.setLogger(ILogger.INFO, newInfoLogger);
logger.log(ILogger.INFO, "Dette er den andre info-meldingen.", null);
assertEquals(String.format(formatString, ILogger.INFO, "Dette er en info-melding.", null),
infoStream.toString().trim(),
"Test the first info stream after switching the info logger and logging another info message");
assertEquals(
String.format(formatString, ILogger.INFO, "Dette er den andre info-meldingen.",
null),
newInfoStream.toString().trim(),
"Test the second info stream after switching the info logger and logging a new info message");
}
}

View File

@@ -0,0 +1,86 @@
package oving6.logger;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.ByteArrayOutputStream;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
public class FilteringLoggerTest {
private ByteArrayOutputStream stream;
private StreamLogger subLogger;
@BeforeEach
public void setUp() {
stream = new ByteArrayOutputStream();
subLogger = new StreamLogger(stream);
}
@Test
@DisplayName("Create logger without severities")
public void testFilteringLoggerNoSeverities() {
FilteringLogger logger = new FilteringLogger(subLogger);
assertFalse(logger.isLogging(ILogger.INFO),
"Test logger without severity for info-logging");
assertFalse(logger.isLogging(ILogger.WARNING),
"Test logger without severity for warning-logging");
assertFalse(logger.isLogging(ILogger.ERROR),
"Test logger without severity for error-logging");
}
@Test
@DisplayName("Create logger with error and info")
public void testFilteringLoggerErrorAndInfo() {
FilteringLogger logger = new FilteringLogger(subLogger, ILogger.ERROR, ILogger.INFO);
assertTrue(logger.isLogging(ILogger.INFO), "Test error and info logger for info-logging");
assertFalse(logger.isLogging(ILogger.WARNING),
"Test error and info logger for warning-logging");
assertTrue(logger.isLogging(ILogger.ERROR), "Test error and info logger for error-logging");
}
@Test
@DisplayName("Create logger with warning, set error")
public void testFilteringLoggerWarningSetIsLoggingError() {
FilteringLogger logger = new FilteringLogger(subLogger, ILogger.WARNING);
assertFalse(logger.isLogging(ILogger.INFO), "Test warning logger for info-logging");
assertTrue(logger.isLogging(ILogger.WARNING), "Test warning logger for warning-logging");
assertFalse(logger.isLogging(ILogger.ERROR), "Test warning logger for error-logging");
logger.setIsLogging(ILogger.ERROR, true);
assertFalse(logger.isLogging(ILogger.INFO),
"Set error-logging for warning logger and test for info-logging");
assertTrue(logger.isLogging(ILogger.WARNING),
"Set error-logging for warning logger and test for warning-logging");
assertTrue(logger.isLogging(ILogger.ERROR),
"Set error-logging for warning logger and test for error-logging");
}
@Test
@DisplayName("Logger with severity ERROR")
public void testErrorLogging() {
IllegalStateException exception = new IllegalStateException();
FilteringLogger logger = new FilteringLogger(subLogger, ILogger.ERROR);
String formatString = "%s: %s (%s)";
subLogger.setFormatString(formatString);
logger.log(ILogger.ERROR, "Noe er feil!", exception);
assertEquals(String.format(formatString, ILogger.ERROR, "Noe er feil!", exception),
stream.toString().trim(), "Test the format of error message after logging");
}
@Test
@DisplayName("Logger with severity INFO in ERROR logger")
public void testInfoToErrorLogger() {
IllegalStateException exception = new IllegalStateException();
FilteringLogger logger = new FilteringLogger(subLogger, ILogger.ERROR);
String formatString = "%s: %s (%s)";
subLogger.setFormatString(formatString);
logger.log(ILogger.INFO, "Noe er feil!", exception);
assertEquals("", stream.toString(),
"Test the stream after logging info message in error logger");
}
}

View File

@@ -0,0 +1,49 @@
package oving6.logger;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.ByteArrayOutputStream;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
public class StreamLoggerTest {
private static final String formatString = "%s: %s (%s)";
private static final String melding = "En melding ble logget!";
private ByteArrayOutputStream stream;
private StreamLogger logger;
@BeforeEach
public void setUp() {
stream = new ByteArrayOutputStream();
logger = new StreamLogger(stream);
}
@Test
@DisplayName("Logs info message")
public void testLog() {
logger.log(ILogger.INFO, melding, null);
assertTrue(stream.toString().contains(melding),
"Test that the stream contains the message after it has been logged");
assertTrue(stream.toString().contains(ILogger.INFO),
"Test that the stream contains a message of type info after it has been logged");
}
@Test
@DisplayName("Logs exception")
public void testLogException() {
assertThrows(IllegalArgumentException.class, () -> {
logger.setFormatString(null);
}, "Test that IllegalArgumentException is thrown when the format is null");
IllegalStateException exception = new IllegalStateException();
logger.setFormatString(formatString);
logger.log(ILogger.INFO, melding, exception);
assertEquals(String.format(formatString, ILogger.INFO, melding, exception),
stream.toString().trim(),
"Test the format of the message that was logged with an exception");
}
}

View File

@@ -0,0 +1,77 @@
package oving6.office;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
public class ClerkTest {
private Clerk clerk;
private Printer printer;
@BeforeEach
public void setUp() {
printer = new Printer();
clerk = new Clerk(printer);
}
@Test
@DisplayName("Perform calculations")
public void testDoCalculations() {
assertEquals(0, clerk.getTaskCount(),
"Testing the initialization of the number of tasks performed");
double calc1 = clerk.doCalculations((x, y) -> x + y, 2.0, 3.5);
assertEquals(5.5, calc1, "Testing calculation with addition: 2.0 + 3.5");
assertEquals(1, clerk.getTaskCount(), "Testing the number of tasks after 1 calculation");
double calc2 = clerk.doCalculations((x, y) -> x / y, 2.0, 4.0);
assertEquals(0.5, calc2, "Testing calculation with division: 2.0/4.0");
assertEquals(2, clerk.getTaskCount(), "Testing the number of tasks after two calculations");
}
@Test
@DisplayName("Print documents")
public void testPrintDocuments() {
assertEquals(0, clerk.getTaskCount(),
"Testing the initialization of the number of tasks performed");
// Print a document
clerk.printDocument("document1");
assertTrue(printer.getPrintHistory(clerk).contains("document1"),
"Testing if the document that was printed was added to the printer history");
assertEquals(1, clerk.getTaskCount(), "Testing the number of tasks after 1 print");
assertEquals(1, printer.getPrintHistory(clerk).size(),
"Testing the number of prints in the history after 1 print");
// Print another document
clerk.printDocument("document2");
assertTrue(printer.getPrintHistory(clerk).contains("document2"),
"Testing if document 2 that was printed was added to the printer history");
assertEquals(2, clerk.getTaskCount(), "Testing the number of tasks after 2 prints");
assertEquals(2, printer.getPrintHistory(clerk).size(),
"Testing the number of prints in the history after 2 prints");
}
@Test
@DisplayName("Retrieve task count")
public void testTaskCount() {
assertEquals(0, clerk.getTaskCount(),
"Testing the initialization of the number of tasks performed");
clerk.printDocument("document1");
assertEquals(1, clerk.getTaskCount(), "Testing the number of tasks after 1 print");
clerk.doCalculations((x, y) -> x + y, 2.0, 3.5);
assertEquals(2, clerk.getTaskCount(),
"Testing the number of tasks after 1 print and 1 calculation");
}
@Test
@DisplayName("Retrieve resource count")
public void testResourceCount() {
assertEquals(1, clerk.getResourceCount(), "Testing the number of resources for one worker");
}
}

View File

@@ -0,0 +1,123 @@
package oving6.office;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.ArrayList;
import java.util.List;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
public class ManagerTest {
private Clerk clerk;
private Manager manager;
private Printer printer;
@BeforeEach
public void setUp() {
printer = new Printer();
clerk = new Clerk(printer);
manager = new Manager(List.of(clerk));
}
@Test
@DisplayName("Create Manager with empty Employee collection")
public void testNoEmployeesConstructor() {
assertThrows(IllegalArgumentException.class, () -> {
new Manager(new ArrayList<Employee>());
}, "Test creating a new Manager with an empty Employee collection");
}
@Test
@DisplayName("Check getResourceCount without middle managers")
public void testResourceCount() {
assertEquals(2, manager.getResourceCount(),
"Test the number of resources for a manager without middle managers");
}
@Test
@DisplayName("Check getResourceCount with middle managers")
public void testMiddleManagementResourceCount() {
Manager topManager = new Manager(List.of(manager));
assertEquals(3, topManager.getResourceCount(),
"Test the number of resources with middle managers");
}
@Test
@DisplayName("Perform a calculation")
public void testDoCalculations() {
assertEquals(0, clerk.getTaskCount(),
"Test the initialization of the number of tasks for a worker");
assertEquals(0, manager.getTaskCount(),
"Test the initialization of the number of tasks for a manager");
double calc = manager.doCalculations((x, y) -> x + y, 2.0, 3.5);
assertEquals(5.5, calc, "Test calculation with addition: 2.0 + 3.5");
assertEquals(1, clerk.getTaskCount(),
"Test the number of tasks for a worker after 1 calculation");
assertEquals(1, manager.getTaskCount(),
"Test the number of tasks for a manager after 1 calculation");
}
@Test
@DisplayName("Print a document")
public void testPrintDocuments() {
manager.printDocument("document1");
assertTrue(printer.getPrintHistory(clerk).contains("document1"),
"Test that the printer history contains the document that was printed");
assertEquals(1, clerk.getTaskCount(),
"Test the number of tasks for a worker after 1 print");
assertEquals(1, manager.getTaskCount(),
"Test the number of tasks for a manager after 1 print");
assertEquals(1, printer.getPrintHistory(clerk).size(),
"Test the number of prints in the printer history after 1 print");
}
@Test
@DisplayName("Check task count")
public void testTaskCount() {
assertEquals(0, clerk.getTaskCount(),
"Test the initialization of the number of tasks for a worker");
assertEquals(0, manager.getTaskCount(),
"Test the initialization of the number of tasks for a manager");
manager.printDocument("document");
assertEquals(1, clerk.getTaskCount(),
"Test the number of tasks for a worker after 1 print");
assertEquals(1, manager.getTaskCount(),
"Test the number of tasks for a manager after 1 print");
manager.doCalculations((x, y) -> x + y, 2.0, 3.5);
assertEquals(2, clerk.getTaskCount(),
"Test the number of tasks for a worker after 1 print and 1 calculation");
assertEquals(2, manager.getTaskCount(),
"Test the number of tasks for a manager after 1 print and 1 calculation");
}
@Test
@DisplayName("Multiple clerks")
public void testSeveralClerks() {
Clerk secondClerk = new Clerk(printer);
Manager multiManager = new Manager(List.of(clerk, secondClerk));
assertEquals(1, clerk.getResourceCount(), "Test the number of resources for worker #1");
assertEquals(3, multiManager.getResourceCount(),
"Test the number of resources for a manager with two workers");
assertEquals(1, secondClerk.getResourceCount(), "Test the resources for worker #2");
multiManager.printDocument("document");
assertEquals(1, multiManager.getTaskCount(),
"Test the number of tasks for a manager after 1 print");
assertTrue(
(clerk.getTaskCount() == 1 || secondClerk.getTaskCount() == 1)
&& (clerk.getTaskCount() == 0 || secondClerk.getTaskCount() == 0),
"Test that only one of the workers has performed a task after 1 print");
double calc = multiManager.doCalculations((x, y) -> x + y, 2.0, 3.5);
assertEquals(5.5, calc, "Test calculation with addition: 2.0 + 3.5");
assertEquals(2, multiManager.getTaskCount(),
"Test the number of tasks for a manager after 1 print and 1 calculation");
}
}

View File

@@ -0,0 +1,97 @@
package oving6.office;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
public class PrinterTest {
private Clerk clerk1;
private Clerk clerk2;
private Printer printer;
@BeforeEach
public void setUp() {
printer = new Printer();
clerk1 = new Clerk(printer);
clerk2 = new Clerk(printer);
}
@Test
@DisplayName("Testing printing")
public void testPrintDocument() {
assertThrows(IllegalArgumentException.class, () -> {
printer.printDocument(null, clerk1);
}, "Test that an exception is thrown when the document is null");
assertThrows(IllegalArgumentException.class, () -> {
printer.printDocument("document1", null);
}, "Test that an exception is thrown when the worker is null");
}
@Test
@DisplayName("Only one printer printing")
public void testPrintSingleClerk() {
assertEquals(0, printer.getPrintHistory(clerk1).size(),
"Test initialization of the number of prints in the printer history");
printer.printDocument("document1", clerk1);
assertEquals(1, printer.getPrintHistory(clerk1).size(),
"Test the number of prints in the history after 1 print");
assertTrue(printer.getPrintHistory(clerk1).contains("document1"),
"Test that the document that was printed is in the history");
printer.printDocument("document2", clerk1);
assertEquals(2, printer.getPrintHistory(clerk1).size(),
"Test the number of prints in the history after 2 prints");
assertTrue(printer.getPrintHistory(clerk1).contains("document2"),
"Test that document 2 that was printed is in the history");
}
@Test
@DisplayName("Multiple printers printing")
public void testPrintMultipleClerks() {
assertEquals(0, printer.getPrintHistory(clerk1).size(),
"Test initialization of printer history for worker1");
assertEquals(0, printer.getPrintHistory(clerk2).size(),
"Test initialization of printer history for worker2");
// Print document for Clerk 1
printer.printDocument("document1", clerk1);
assertEquals(1, printer.getPrintHistory(clerk1).size(),
"Test the number of prints in the history for worker1 after printing 1 document");
assertTrue(printer.getPrintHistory(clerk1).contains("document1"),
"Test that the history of worker1 contains the document that was printed");
assertEquals(0, printer.getPrintHistory(clerk2).size(),
"Test the number of prints in the history for worker2 after worker1 has printed "
+ "a document");
// Print document for Clerk 2
printer.printDocument("document2", clerk2);
assertEquals(1, printer.getPrintHistory(clerk2).size(),
"Test the number of prints in the history for worker2 after printing a document");
assertTrue(printer.getPrintHistory(clerk2).contains("document2"),
"Test that the history of worker2 contains the document that was printed");
assertEquals(1, printer.getPrintHistory(clerk1).size(),
"Test the number of prints in the history for worker1 after both worker1 and "
+ "worker2 have printed 1 document each");
}
@Test
@DisplayName("Modifying printer history is not allowed")
public void testPrintHistoryModification() {
printer.printDocument("document1", clerk1);
printer.printDocument("document2", clerk1);
assertEquals(2, printer.getPrintHistory(clerk1).size(),
"Test the number of prints in the history after 2 prints");
// Remove a document and check that the printer history remains unchanged
printer.getPrintHistory(clerk1).remove("document1");
assertEquals(2, printer.getPrintHistory(clerk1).size(),
"Test the number of prints in the history after 2 prints and attempting to "
+ "remove 1 of them");
}
}

View File

@@ -0,0 +1,124 @@
package oving6.stock;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
public class SmartStockTest {
private SmartStock stock;
private double oldPrice;
private double newPrice;
// Used to check that listeners work
private double oldPriceListener;
private double newPriceListener;
private void setPriceForListener(double oldPrice, double newPrice) {
oldPriceListener = oldPrice;
newPriceListener = newPrice;
}
private void setPriceCheckListener(String contextMessage, double newPrice,
double expectedOldPrice, double expectedNewPrice) {
// Update the price
this.oldPrice = this.newPrice;
this.newPrice = newPrice;
stock.setPrice(newPrice);
// Check that the listener has received the change
assertEquals(expectedOldPrice, this.oldPriceListener,
contextMessage + " -> Test old price for listener after updating price from "
+ oldPrice + " to " + newPrice);
assertEquals(expectedNewPrice, this.newPriceListener,
contextMessage + " -> Test new price for listener after updating price from "
+ oldPrice + " to " + newPrice);
}
@BeforeEach
public void setUp() {
stock = new SmartStock("APPL", 110.0);
}
@Test
@DisplayName("Test constructor")
public void testConstructor() {
assertEquals("APPL", stock.getTicker(), "Test ticker");
assertEquals(110.0, stock.getPrice(), "Test stock price");
}
@Test
@DisplayName("Negative stock price throws error")
public void testSetNegativePrice() {
assertThrows(IllegalArgumentException.class, () -> {
stock.setPrice(-20.0);
}, "Test setting negative stock price");
}
@Test
@DisplayName("Stock price equal to zero throws error")
public void testSetZeroPrice() {
assertThrows(IllegalArgumentException.class, () -> {
stock.setPrice(0);
}, "Test setting stock price equal to zero");
}
@Test
@DisplayName("Add listener")
public void testStockListener() {
StockListener listener = (Stock stock, double oldPrice, double newPrice) -> this
.setPriceForListener(oldPrice, newPrice);
stock.addStockListener(listener);
this.setPriceCheckListener("Listener on all", 118.0, 110.0, 118.0);
assertEquals(118.0, stock.getPrice(), "Test stock price after updating price");
this.setPriceCheckListener("Listener on all", 121.0, 118.0, 121.0);
assertEquals(121.0, stock.getPrice(), "Test stock price after updating price twice");
}
@Test
@DisplayName("Test listener on price interval")
public void testIntervalListener() {
StockListener listener = (Stock stock, double oldPrice, double newPrice) -> this
.setPriceForListener(oldPrice, newPrice);
stock.addStockListener(listener, 110.0, 120.0);
// Price within the interval does not notify the listener
this.setPriceCheckListener("Listener on price interval", 118.0, 0.0, 0.0);
assertEquals(118.0, stock.getPrice(), "Test stock price after updating price");
// Price outside the interval notifies the listener
this.setPriceCheckListener("Listener on price interval", 121.0, 118.0, 121.0);
assertEquals(121.0, stock.getPrice(),
"Test stock price after updating price for the second time");
// Price within the interval does not notify the listener (expected values remain unchanged)
this.setPriceCheckListener("Listener on price interval", 115.0, 118.0, 121.0);
assertEquals(115.0, stock.getPrice(),
"Test stock price after updating price for the third time");
}
@Test
@DisplayName("Test listener on difference")
public void testDifferenceListener() {
StockListener listener = (Stock stock, double oldPrice, double newPrice) -> this
.setPriceForListener(oldPrice, newPrice);
stock.addStockListener(listener, 10.0);
// Price with a difference less than 10 does not notify the listener
this.setPriceCheckListener("Listener on difference", 118.0, 0.0, 0.0);
assertEquals(118.0, stock.getPrice());
// Price with a difference greater than 10 notifies the listener
this.setPriceCheckListener("Listener on difference", 121.0, 110.0, 121.0);
assertEquals(121.0, stock.getPrice());
// Price with a difference less than 10 does not notify the listener (expected values remain
// unchanged)
this.setPriceCheckListener("Listener on difference", 115.0, 110.0, 121.0);
assertEquals(115.0, stock.getPrice());
}
}

View File

@@ -0,0 +1,116 @@
package oving6.stock;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
public class StockIndexTest {
private static final double applePrice = 534.98;
private static final double facebookPrice = 67.80;
private static final double epsilon = 0.000001;
private Stock apple;
private Stock facebook;
private StockIndex index0;
private StockIndex index1;
private StockIndex indexN;
@BeforeEach
public void setUp() {
apple = new Stock("AAPL", applePrice);
facebook = new Stock("FB", facebookPrice);
index0 = new StockIndex("OSEBX");
index1 = new StockIndex("OSEBX", facebook);
indexN = new StockIndex("OSEBX", facebook, apple);
}
@Test
@DisplayName("Test constructor")
public void testConstructor() {
assertEquals(0.0, index0.getIndex(), epsilon, "Test the value of the index with 0 stocks");
assertEquals(facebookPrice, index1.getIndex(), epsilon,
"Test the value of the index with 1 stock");
assertEquals(facebookPrice + applePrice, indexN.getIndex(), epsilon,
"Test the value of the index with 2 stocks");
assertThrows(IllegalArgumentException.class, () -> {
new StockIndex(null);
}, "Test constructor with null name");
assertThrows(IllegalArgumentException.class, () -> {
new StockIndex("OSEBX", apple, null, facebook);
}, "Test constructor with null stocks");
}
@Test
@DisplayName("Add stock")
public void testAddStock() {
assertEquals(0.0, index0.getIndex(), epsilon, "Test the value of the index with 0 stocks");
index0.addStock(facebook);
assertEquals(facebookPrice, index0.getIndex(), epsilon,
"Test the value of the index after adding 1 stock");
assertThrows(IllegalArgumentException.class, () -> {
index0.addStock(null);
}, "Test adding null stock");
}
@Test
@DisplayName("Add the same stock twice")
public void testAddDuplicateStocks() {
assertEquals(0.0, index0.getIndex(), epsilon, "Test the value of the index with 0 stocks");
index0.addStock(facebook);
assertEquals(facebookPrice, index0.getIndex(), epsilon,
"Test the value of the index after adding 1 stock");
index0.addStock(facebook);
assertEquals(facebookPrice, index0.getIndex(), epsilon,
"Test the value of the index after adding a stock that is already in the index");
}
@Test
@DisplayName("Remove stock")
public void testRemoveStock() {
assertEquals(facebookPrice + applePrice, indexN.getIndex(), epsilon,
"Test the value of the index with 2 stocks");
indexN.removeStock(apple);
assertEquals(facebookPrice, indexN.getIndex(), epsilon,
"Test the value of the index after removing 1 stock");
indexN.removeStock(apple);
assertEquals(facebookPrice, indexN.getIndex(), epsilon,
"Test the value of the index after removing 1 stock that was not in the index");
indexN.removeStock(facebook);
assertEquals(0.0, indexN.getIndex(), epsilon,
"Test the value of the index after removing the only stock in the index");
}
@Test
@DisplayName("Change stock price")
public void testChangePrice() {
double facebookPrice2 = 67.0;
double facebookPrice3 = 69.0;
facebook.setPrice(facebookPrice2);
assertEquals(facebookPrice2, index1.getIndex(), epsilon,
"Test the value of the index with 1 stock after changing the stock price");
assertEquals(facebookPrice2 + applePrice, indexN.getIndex(), epsilon,
"Test the value of the index with 2 stocks after changing the price of 1 stock");
facebook.setPrice(facebookPrice3);
assertEquals(facebookPrice3, index1.getIndex(), epsilon,
"Test the value of the index with 1 stock after changing the stock price a "
+ "second time");
assertEquals(facebookPrice3 + applePrice, indexN.getIndex(), epsilon,
"Test the value of the index with 2 stocks after changing the price of 1 stock a "
+ "second time");
}
}

View File

@@ -0,0 +1,89 @@
package oving6.stock;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
public class StockTest {
private Stock stock;
private double oldPrice;
private double newPrice;
// Used to check that listeners work
private double oldPriceListener;
private double newPriceListener;
private void setPriceForListener(double oldPrice, double newPrice) {
oldPriceListener = oldPrice;
newPriceListener = newPrice;
}
private void setPriceCheckListener(double newPrice, double expectedOldPrice,
double expectedNewPrice) {
// Update the price
this.oldPrice = this.newPrice;
this.newPrice = newPrice;
stock.setPrice(newPrice);
// Check that the listener has received the change
assertEquals(expectedOldPrice, this.oldPriceListener,
"Test old price for listener after updating price from " + oldPrice + " to "
+ newPrice);
assertEquals(expectedNewPrice, this.newPriceListener,
"Test new price for listener after updating price from " + oldPrice + " to "
+ newPrice);
}
@BeforeEach
public void setUp() {
stock = new Stock("APPL", 110.0);
oldPrice = 0.0;
newPrice = 110.0;
oldPriceListener = 0.0;
newPriceListener = 0.0;
}
@Test
@DisplayName("Test constructor")
public void testConstructor() {
assertEquals("APPL", stock.getTicker(), "Test ticker");
assertEquals(110.0, stock.getPrice(), "Test stock price");
assertThrows(IllegalArgumentException.class, () -> {
new Stock(null, 110.0);
}, "Test constructor with null ticker");
}
@Test
@DisplayName("Negative stock price throws error")
public void testSetNegativePrice() {
assertThrows(IllegalArgumentException.class, () -> {
stock.setPrice(-20.0);
}, "Test setting negative stock price");
}
@Test
@DisplayName("Stock price equal to zero throws error")
public void testSetZeroPrice() {
assertThrows(IllegalArgumentException.class, () -> {
stock.setPrice(0);
}, "Test setting stock price equal to zero");
}
@Test
@DisplayName("Add listener")
public void testStockListener() {
StockListener listener = (Stock stock, double oldPrice, double newPrice) -> this
.setPriceForListener(oldPrice, newPrice);
stock.addStockListener(listener);
this.setPriceCheckListener(118.0, 110.0, 118.0);
assertEquals(118.0, stock.getPrice(), "Test stock price after updating price");
this.setPriceCheckListener(121.0, 118.0, 121.0);
assertEquals(121.0, stock.getPrice(), "Test stock price after updating price twice");
}
}