Logging and docs added to classes Person, Place and Player #27 #28 #50

Merged
brandleo merged 10 commits from logging_and_docs into main 2022-05-13 17:49:39 +02:00
20 changed files with 359 additions and 117 deletions
Showing only changes of commit f8d12dafa7 - Show all commits

View File

@ -26,6 +26,8 @@ dependencies {
// Use JUnit Jupiter for testing.
testImplementation 'org.junit.jupiter:junit-jupiter:5.8.1'
testImplementation 'org.mockito:mockito-core:4.3.+'
// This dependency is used by the application.
implementation 'com.google.guava:guava:30.1.1-jre'
@ -37,7 +39,9 @@ application {
mainClass = 'ch.zhaw.projekt2.turnierverwaltung.App'
}
tasks.named('test') {
test {
// Use JUnit Platform for unit tests.
useJUnitPlatform()
}

View File

@ -37,11 +37,6 @@ public abstract class FXController {
factoryDecorator.addListener(listener);
}
protected void removeListener(){
tournamentDecorator.removeListener(listener);
factoryDecorator.removeListener(listener);
}
protected TournamentDecorator getTournamentDecorator() {
return tournamentDecorator;
}

View File

@ -2,7 +2,6 @@ package ch.zhaw.projekt2.turnierverwaltung;
import ch.zhaw.projekt2.turnierverwaltung.main.gameScheduleView.GameController;
import ch.zhaw.projekt2.turnierverwaltung.main.gameScheduleView.GameDecorator;
import ch.zhaw.projekt2.turnierverwaltung.main.tournamentList.TournamentListController;
import javafx.fxml.FXMLLoader;
import javafx.geometry.Insets;
import javafx.scene.control.Label;
@ -11,16 +10,15 @@ import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import java.io.IOException;
import java.net.URL;
public class Factory {
private TournamentDecorator tournamentDecorator;
private FileIO fileIO;
//TODO save views instead of recreate them.
public Factory(FileIO fileIO, TournamentDecorator tournamentDecorator) {
this.fileIO = fileIO;
this.tournamentDecorator = tournamentDecorator;
}
public TournamentDecorator getTournamentDecorator() {
@ -42,25 +40,43 @@ public class Factory {
return null;
}
public void loadTournamentList(BorderPane pane, FactoryDecorator factoryDecorator) {
public void loadAllViews(FactoryDecorator factoryDecorator, BorderPane pane){
for(View view : View.values()){
try {
view.loadView(tournamentDecorator, fileIO, factoryDecorator, pane);
} catch (IOException e) {
e.printStackTrace();
//TODO Handle and logging.
}
}
}
public void showTournamentList(BorderPane pane, FactoryDecorator factoryDecorator) {
tournamentDecorator.setTournament(null);
TournamentListController controller = (TournamentListController) setCenterOfBorderPane(pane, getClass().getResource("tournamentList/tournamentList.fxml"), factoryDecorator);
setCenterOfBorderPane(pane, View.tournamentList);
}
//Can be used to Open new Scene in same Stage.
//This way possible to later give object to Controller
public void loadParticipantFormular(BorderPane pane, FactoryDecorator factoryDecorator) {
setCenterOfBorderPane(pane, getClass().getResource("participantAddFormular/participantFormular.fxml"), factoryDecorator);
public void showParticipantFormular(BorderPane pane, FactoryDecorator factoryDecorator) {
setCenterOfBorderPane(pane, View.participantFormular);
}
public void loadPlacesFormular(BorderPane pane, FactoryDecorator factoryDecorator) {
setCenterOfBorderPane(pane, getClass().getResource("placesAddFormular/PlacesFormular.fxml"), factoryDecorator);
public void showPlacesFormular(BorderPane pane, FactoryDecorator factoryDecorator) {
setCenterOfBorderPane(pane, View.placesFormular);
}
public void loadGameScheduler(BorderPane pane, FactoryDecorator factoryDecorator) {
setCenterOfBorderPane(pane, getClass().getResource("gameScheduleView/GameSchedule.fxml"), factoryDecorator);
public void showGameScheduler(BorderPane pane, FactoryDecorator factoryDecorator) {
setCenterOfBorderPane(pane, View.gameScheduler);
}
private void setCenterOfBorderPane(BorderPane pane, View view) {
FXController controller = null;
pane.setCenter(view.getPane());
resetFooter(pane, true);
}
public GameController loadGameView(VBox box, GameDecorator gameDecorator, FactoryDecorator factoryDecorator) {
try {
FXMLLoader loader = new FXMLLoader(getClass().getResource("gameScheduleView/Game.fxml"));
@ -75,23 +91,6 @@ public class Factory {
return null;
}
private FXController setCenterOfBorderPane(BorderPane pane, URL location, FactoryDecorator factoryDecorator) {
FXController controller = null;
try {
FXMLLoader loader = new FXMLLoader(location);
pane.setCenter(loader.load());
controller = loader.getController();
controller.setup(tournamentDecorator, fileIO, factoryDecorator, pane);
VBox bottom = (VBox) pane.getBottom();
resetFooter(pane, true);
} catch (IOException e) {
e.printStackTrace();
//TODO handle and logging?
}
return controller;
}
public void printMessageToFooter(BorderPane pane, String msg, boolean error) {
VBox bottom = (VBox) pane.getBottom();
Label label = new Label();
@ -131,4 +130,30 @@ public class Factory {
vBox.setBorder(null);
}
public enum View {
tournamentList("tournamentList/tournamentList.fxml"),
participantFormular("participantAddFormular/participantFormular.fxml"),
placesFormular("placesAddFormular/PlacesFormular.fxml"),
gameScheduler("gameScheduleView/GameSchedule.fxml");
private String fxmlFileName;
private Pane pane;
private View(String fxmlFileName) {
this.fxmlFileName = fxmlFileName;
}
public Pane getPane() {
return pane;
}
public void loadView(TournamentDecorator tournamentDecorator, FileIO fileIO, FactoryDecorator factoryDecorator, BorderPane borderPane) throws IOException {
FXMLLoader loader = new FXMLLoader(getClass().getResource(fxmlFileName));
this.pane = loader.load();
FXController controller = loader.getController();
controller.setup(tournamentDecorator, fileIO, factoryDecorator, borderPane);
}
}
}

View File

@ -51,36 +51,40 @@ public class FactoryDecorator implements IsObservable{
try {
factory.setTournament(fileIO.loadTournament(tournamentFile));
openScheduleView();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
clearMessage(false);
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
printMessageToFooter("Fehler beim lesen der Datei.", true);
} //TODO handle and logging
}
public void openTournamentList() {
factory.loadTournamentList((BorderPane) pane, this);
factory.showTournamentList((BorderPane) pane, this);
informListener();
}
public void openParticipantFormular() {
factory.loadParticipantFormular((BorderPane) pane, this);
factory.showParticipantFormular((BorderPane) pane, this);
informListener();
}
public void openPlacesFormular() {
factory.loadPlacesFormular((BorderPane) pane, this);
factory.showPlacesFormular((BorderPane) pane, this);
informListener();
}
public void openScheduleView() {
factory.loadGameScheduler((BorderPane) pane, this);
factory.showGameScheduler((BorderPane) pane, this);
informListener();
}
public void loadGameList(HBox hBoxCenter, TournamentDecorator tournamentDecorator, boolean treeView) {
hBoxCenter.getChildren().clear();
if(tournamentDecorator.getTournament() == null){
return;
}
List<List<Game>> gameList = tournamentDecorator.getTournament().getGameList();
List<GameDecorator> gameDecoratorsList = new ArrayList<>();

View File

@ -19,14 +19,6 @@ public class Game implements Serializable {
this.previousGame2 = previousGame2;
}
public Place getLocation() {
return place;
}
public void setLocation(Place place) {
this.place = place;
}
public int getPoints1() {
return points1;
}

View File

@ -67,4 +67,8 @@ public class Place implements Serializable {
logger.fine("Comparing " + place + " with " + this);
return name.equals(place.getName());
}
public void change(Place place) {
//TODO: If Place gets more developed in future releases
}
}

View File

@ -25,7 +25,8 @@ public class Player extends Person implements Participant {
* @throws InvalidNameException thrown when the name or firstname are not in a valid format
* @throws InvalidPhoneNumberException thrown when the phone number is not in a valid format
*/
public Player(String firstName, String name, String phoneNumber, String dateOfBirth) throws InvalidNameException, InvalidPhoneNumberException {
public Player(String firstName, String name, String phoneNumber, String dateOfBirth) throws InvalidNameException, InvalidPhoneNumberException, InvalidDateException {
super(firstName, name, phoneNumber);
logger.fine("initialized super of Player with firstname, name and phone number");
logger.finer("Setting the date of birth as:" + dateOfBirth);
@ -62,22 +63,26 @@ public class Player extends Person implements Participant {
}
}
/**
* Method to set the date of Birth with a String provided.
*
* @param dateOfBirth to be as a String
*/
public void setDateOfBirth(String dateOfBirth) {
public void setDateOfBirth(String dateOfBirth) throws InvalidDateException {
logger.finer("Trying to set of birth with the String " + dateOfBirth + " provided");
if (dateOfBirth.length() > 0) {
if(dateOfBirth.length() > 0) {
String[] date = dateOfBirth.split("\\.");
try{
this.dateOfBirth = LocalDate.of(Integer.valueOf(date[2]), Integer.valueOf(date[1]), Integer.valueOf(date[0]));
logger.fine("");
logger.fine("Date of birth of" + getName() + " has been set to " + dateOfBirth);
} catch (NumberFormatException | IndexOutOfBoundsException e) {
e.printStackTrace();
logger.warning("Date of birth of " + getName() + " could not be set, leaving at null");
throw new InvalidDateException("Date invalid");
}
} else {
logger.warning("Date of birth of " + getName() + " could not be set, leaving at null");
dateOfBirth = null;
}
}
@ -116,4 +121,16 @@ public class Player extends Person implements Participant {
setDateOfBirth(player.getDateOfBirth());
setPhoneNumber(player.getPhoneNumber());
}
public class InvalidDateException extends Exception {
public InvalidDateException() {
super();
}
public InvalidDateException(String errorMessage) {
super(errorMessage);
}
}
}

View File

@ -108,10 +108,14 @@ public class Tournament implements Serializable {
* Method to add a new Place, also checks if place does already exist.
*
* @param newPlace to be added in the list of all places
* @throws PlaceExistsException if the place already exists
*/
public void addPlace(Place newPlace) throws PlaceExistsException {
places.removeIf(place -> place.equals(newPlace));
public void savePlace(Place newPlace) {
for (Place place : places) {
if (place.equals(newPlace)) {
place.change(newPlace);
return;
}
}
places.add(newPlace);
}
@ -248,7 +252,7 @@ public class Tournament implements Serializable {
* (In the Prototype only the KO-System has full functionality
*/
public enum Type {
KO("KO-System"), GROUPS("Gruppenspiele");
KO("KO-System"); //GROUPS("Gruppenspiele"); //Type GROUPS is not implemented in this prototype.
private String name;
@ -296,20 +300,6 @@ public class Tournament implements Serializable {
}
/**
* Custom Exception thrown when a Place does already exist
*/
public class PlaceExistsException extends Exception {
public PlaceExistsException() {
super();
}
public PlaceExistsException(String errorMessage) {
super(errorMessage);
}
}
/**
* Custom Exception thrown when a Place does not exist
*/

View File

@ -8,6 +8,7 @@ import java.util.Date;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class TournamentDecorator implements IsObservable{
private Tournament tournament;
@ -27,7 +28,7 @@ public class TournamentDecorator implements IsObservable{
}
}
});
executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
executorService = Executors.newFixedThreadPool(1);
}
public void setFactoryDecorator(FactoryDecorator factoryDecorator) {
@ -128,6 +129,9 @@ public class TournamentDecorator implements IsObservable{
} catch (Person.InvalidPhoneNumberException e) {
e.printStackTrace(); //TODO handle and logging
factoryDecorator.printMessageToFooter("Invalide Telefonnummer",true);
} catch (Player.InvalidDateException e) {
e.printStackTrace();
factoryDecorator.printMessageToFooter("Ungültiges Geburtsdatum", true);
}
}
@ -145,13 +149,9 @@ public class TournamentDecorator implements IsObservable{
public void savePlace(String name){
try {
tournament.addPlace(new Place(name));
tournament.savePlace(new Place(name));
factoryDecorator.clearMessage(true);
informListener();
} catch (Tournament.PlaceExistsException e) {
e.printStackTrace(); //TODO handle and logging
factoryDecorator.printMessageToFooter("Ort existiert bereits",true);
} catch (InvalidNameException e) {
e.printStackTrace(); //TODO handle and logging
factoryDecorator.printMessageToFooter("Invalider Ortsname",true);
@ -176,6 +176,11 @@ public class TournamentDecorator implements IsObservable{
}
}
public void closeApplication() throws InterruptedException {
executorService.shutdown();
executorService.awaitTermination(2000, TimeUnit.MILLISECONDS);
}
private class saveTask implements Runnable {
@Override

View File

@ -5,34 +5,48 @@ import ch.zhaw.projekt2.turnierverwaltung.FactoryDecorator;
import ch.zhaw.projekt2.turnierverwaltung.FileIO;
import ch.zhaw.projekt2.turnierverwaltung.TournamentDecorator;
import javafx.application.Application;
import javafx.event.EventHandler;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
import javafx.stage.WindowEvent;
import java.util.logging.Logger;
public class MainWindow extends Application {
private FileIO fileIO = new FileIO(System.getProperty("user.dir") + System.getProperty("file.separator") + "tournierverwaltung_angrynerds");
private FactoryDecorator factoryDecorator;
private TournamentDecorator tournamentDecorator = new TournamentDecorator(fileIO);
private Factory factory = new Factory(fileIO, tournamentDecorator); //TODO make it private!
private Factory factory = new Factory(fileIO, tournamentDecorator);
private static final Logger logger = Logger.getLogger(FileIO.class.getCanonicalName());
@Override
public void start(Stage primaryStage) throws Exception {
BorderPane pane = factory.loadMainWindow();
factoryDecorator = new FactoryDecorator(fileIO, factory, pane);
factory.loadAllViews(factoryDecorator, pane);
tournamentDecorator.setFactoryDecorator(factoryDecorator);
factoryDecorator.openTournamentList();
Scene scene = new Scene(pane);
primaryStage.setScene(scene);
primaryStage.setMinHeight(600);
primaryStage.setMinWidth(800);
primaryStage.setMaximized(true);
primaryStage.setResizable(true);
primaryStage.setFullScreen(false);
primaryStage.show();
}
@Override
public void stop() {
try {
super.stop();
tournamentDecorator.closeApplication();
} catch (Exception e) {
logger.warning("Exception while closing application");
}
}
}

View File

@ -1,6 +1,7 @@
package ch.zhaw.projekt2.turnierverwaltung.main;
import ch.zhaw.projekt2.turnierverwaltung.FXController;
import javafx.application.Platform;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
@ -13,7 +14,7 @@ public class MainWindowController extends FXController {
@FXML
void closeApplication(ActionEvent event) {
Platform.exit();
}
@Override

View File

@ -0,0 +1,26 @@
package ch.zhaw.projekt2.turnierverwaltung.main.gameScheduleView;
import javafx.scene.control.Alert;
import javafx.scene.control.ButtonBar;
import javafx.scene.control.ButtonType;
public class AlertNewSchedule extends Alert {
private ButtonType yesButton = new ButtonType("Ja", ButtonBar.ButtonData.YES);
private ButtonType noButton = new ButtonType("Nein", ButtonBar.ButtonData.NO);
private boolean result;
public AlertNewSchedule() {
super(AlertType.WARNING);
setTitle("Neu erstellen");
setHeaderText("Spielplan neu erstellen?");
setContentText("Sind Sie sicher, dass Sie den Spielplan neu erstellen moechten?\nAlle Spielfortschritte gehen daraufhin verloren!");
getButtonTypes().setAll(yesButton,noButton);
}
public boolean showAndGetResult() {
showAndWait().ifPresent(input -> {
result = input == yesButton;
});
return result;
}
}

View File

@ -74,7 +74,7 @@ public class GameController extends FXController{
public void setup(TournamentDecorator tournamentDecorator, FileIO fileIO, FactoryDecorator factoryDecorator, Pane pane, GameDecorator gameDecorator) {
setTournamentDecorator(tournamentDecorator);
this.gameDecorator = gameDecorator;
placesChoiceBox.getSelectionModel().selectedItemProperty().addListener((ObservableValue<? extends Place> observable, Place oldValue, Place newValue) -> saveGamePlace(newValue));
placesChoiceBox.getSelectionModel().selectedItemProperty().addListener((ObservableValue<? extends Place> observable, Place oldValue, Place newValue) -> saveGamePlace(newValue == null ? oldValue : newValue));
}
}

View File

@ -1,7 +1,6 @@
package ch.zhaw.projekt2.turnierverwaltung.main.gameScheduleView;
import ch.zhaw.projekt2.turnierverwaltung.FXController;
import ch.zhaw.projekt2.turnierverwaltung.Tournament;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
@ -30,24 +29,28 @@ public class GameScheduleController extends FXController {
@FXML
void createNewSchedule(ActionEvent event) {
if (getTournamentDecorator().getTournament().getGameList().size() > 0) {
AlertNewSchedule alert = new AlertNewSchedule();
if (alert.showAndGetResult()) {
getTournamentDecorator().createNewGameSchedule();
}
} else {
getTournamentDecorator().createNewGameSchedule();
}
}
@FXML
void openPlacesFormular(ActionEvent event) {
removeListener();
getFactoryDecorator().openPlacesFormular();
}
@FXML
void openParticipantFormular(ActionEvent event) {
removeListener();
getFactoryDecorator().openParticipantFormular();
}
@FXML
void closeTournament(ActionEvent event) {
removeListener();
getFactoryDecorator().openTournamentList();
}

View File

@ -3,6 +3,7 @@ package ch.zhaw.projekt2.turnierverwaltung.main.participantAddFormular;
import ch.zhaw.projekt2.turnierverwaltung.FXController;
import ch.zhaw.projekt2.turnierverwaltung.Participant;
import ch.zhaw.projekt2.turnierverwaltung.Player;
import ch.zhaw.projekt2.turnierverwaltung.Tournament;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
@ -97,12 +98,16 @@ public class ParticipantFormularController extends FXController {
@FXML
void close(ActionEvent event) {
removeListener();
getFactoryDecorator().openScheduleView();
}
@Override
public void loadContent() {
participantListView.setItems(getTournamentDecorator().getTournament().getParticipants());
Tournament tournament = getTournamentDecorator().getTournament();
if(tournament != null){
participantListView.setItems(tournament.getParticipants());
} else {
participantListView.getItems().clear();
}
}
}

View File

@ -3,6 +3,7 @@ package ch.zhaw.projekt2.turnierverwaltung.main.placesAddFormular;
import ch.zhaw.projekt2.turnierverwaltung.FXController;
import ch.zhaw.projekt2.turnierverwaltung.Place;
import ch.zhaw.projekt2.turnierverwaltung.Player;
import ch.zhaw.projekt2.turnierverwaltung.Tournament;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
@ -73,12 +74,16 @@ public class PlacesFormularController extends FXController {
@FXML
void close(ActionEvent event) {
removeListener();
getFactoryDecorator().openScheduleView();
}
@Override
public void loadContent() {
placeListView.setItems(getTournamentDecorator().getTournament().getPlaces());
Tournament tournament = getTournamentDecorator().getTournament();
if(tournament != null){
placeListView.setItems(tournament.getPlaces());
} else {
placeListView.getItems().clear();
}
}
}

View File

@ -21,9 +21,7 @@ public class AlertDelete extends Alert {
public boolean showAndGetResult() {
result = false;
showAndWait().ifPresent(type -> {
if (type == yesButton) {
result = true;
}
result = type == yesButton;
});
return result;
}

View File

@ -62,7 +62,6 @@ public class TournamentListController extends FXController {
@FXML
void openTournament(ActionEvent event) {
removeListener();
FileIO.TournamentFile tournamentFile = tournamentListView.getSelectionModel().getSelectedItems().get(0);
getFactoryDecorator().openTournament(tournamentFile);
}

View File

@ -1,15 +1,29 @@
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.geometry.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<?import javafx.geometry.Insets?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.control.CheckBox?>
<?import javafx.scene.control.ScrollPane?>
<?import javafx.scene.layout.BorderPane?>
<?import javafx.scene.layout.HBox?>
<BorderPane maxHeight="1.7976931348623157E308" maxWidth="1.7976931348623157E308" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/11.0.2" xmlns:fx="http://javafx.com/fxml/1" fx:controller="ch.zhaw.projekt2.turnierverwaltung.main.gameScheduleView.GameScheduleController">
<BorderPane maxHeight="1.7976931348623157E308" maxWidth="1.7976931348623157E308" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/18" xmlns:fx="http://javafx.com/fxml/1" fx:controller="ch.zhaw.projekt2.turnierverwaltung.main.gameScheduleView.GameScheduleController">
<center>
<ScrollPane maxHeight="1.7976931348623157E308" maxWidth="1.7976931348623157E308" prefHeight="200.0" prefWidth="200.0" BorderPane.alignment="CENTER">
<content>
<HBox fx:id="hBoxCenter" maxHeight="1.7976931348623157E308" maxWidth="1.7976931348623157E308" prefHeight="324.0" prefWidth="600.0" />
</content>
</ScrollPane>
</center>
<top>
<HBox alignment="TOP_RIGHT" prefHeight="100.0" prefWidth="200.0" BorderPane.alignment="CENTER">
<HBox alignment="CENTER_LEFT" prefHeight="100.0" prefWidth="200.0" BorderPane.alignment="CENTER">
<children>
<CheckBox fx:id="treeView" mnemonicParsing="false" onAction="#changeView" selected="true" text="Baumansicht" />
<Button fx:id="createScheduleBtn" mnemonicParsing="false" onAction="#createNewSchedule" text="Create New Game Schedule">
<CheckBox fx:id="treeView" mnemonicParsing="false" onAction="#changeView" selected="true" text="Baumansicht">
<HBox.margin>
<Insets left="20.0" right="20.0" />
</HBox.margin>
</CheckBox>
<Button fx:id="createScheduleBtn" mnemonicParsing="false" onAction="#createNewSchedule" text="Spielplan neu erstellen">
<HBox.margin>
<Insets right="20.0" />
</HBox.margin>
@ -24,18 +38,12 @@
<Insets right="20.0" />
</HBox.margin>
</Button>
<Button fx:id="closeTournamentBtn" layoutX="470.0" layoutY="10.0" mnemonicParsing="false" onAction="#closeTournament" text="Close Tournament">
<Button fx:id="closeTournamentBtn" mnemonicParsing="false" onAction="#closeTournament" text="Close Tournament">
<HBox.margin>
<Insets right="20.0" />
</HBox.margin></Button>
</HBox.margin>
</Button>
</children>
</HBox>
</top>
<center>
<ScrollPane maxHeight="1.7976931348623157E308" maxWidth="1.7976931348623157E308" prefHeight="200.0" prefWidth="200.0" BorderPane.alignment="CENTER">
<content>
<HBox fx:id="hBoxCenter" maxHeight="1.7976931348623157E308" maxWidth="1.7976931348623157E308" prefHeight="324.0" prefWidth="600.0" />
</content>
</ScrollPane>
</center>
</BorderPane>

View File

@ -0,0 +1,147 @@
package ch.zhaw.projekt2.turnierverwaltung;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@DisplayName("TournamentTest")
public class TournamentTest {
@Nested
@DisplayName("KOMode")
public class KOMode {
private Tournament tournament;
@BeforeEach
void setup() {
try {
tournament = new Tournament("Name", Tournament.Type.KO);
} catch (InvalidNameException e) {
e.printStackTrace();
fail();
} catch (Tournament.InvalidTypeException e) {
e.printStackTrace();
fail();
}
}
@Test
@DisplayName("Test invalid instance")
void makeInvalidInstance() {
assertThrows(InvalidNameException.class, () -> new Tournament(".", Tournament.Type.KO));
}
@Test
@DisplayName("Save Participant")
void saveParticipantTest() {
//Checks if one Participant gets added
Participant participantOne = Mockito.mock(Player.class);
when(participantOne.equals(any(Participant.class))).thenReturn(false);
assertEquals(0, tournament.getParticipants().size());
tournament.saveParticipant(participantOne);
assertEquals(1, tournament.getParticipants().size());
//Checks if a second Participant gets added
Participant participantTwo = Mockito.mock(Player.class);
tournament.saveParticipant(participantTwo);
assertEquals(2, tournament.getParticipants().size());
//Checks if a allready added Particpant does not get added
when(participantOne.equals(any(Participant.class))).thenReturn(true);
tournament.saveParticipant(participantTwo);
assertEquals(2, tournament.getParticipants().size());
}
@Test
@DisplayName("Remove Participant")
void removeParticipantTest() {
Participant participant = Mockito.mock(Player.class);
//Checks if Error is thrown if Participant not in list
assertThrows(Tournament.ParticipantNotExistsException.class, () -> tournament.removeParticipant(participant));
//Checks if participant gets removed
tournament.saveParticipant(participant);
assertEquals(1, tournament.getParticipants().size());
try {
tournament.removeParticipant(participant);
assertEquals(0, tournament.getParticipants().size());
} catch (Tournament.ParticipantNotExistsException e) {
fail();
}
}
@Test
@DisplayName("Add Place")
void addPlaceTest() {
Place place = mock(Place.class);
when(place.equals(any(Place.class))).thenReturn(false).thenReturn(true);
assertEquals(0, tournament.getPlaces().size());
tournament.savePlace(place);
assertEquals(1, tournament.getPlaces().size());
tournament.savePlace(place);
assertEquals(2, tournament.getPlaces().size());
tournament.savePlace(place);
assertEquals(2, tournament.getPlaces().size());
}
@Test
@DisplayName("Remove Place")
void removePlaceTest() {
Place place = mock(Place.class);
assertThrows(Tournament.PlaceNotExistsException.class, () -> tournament.removePlace(place));
tournament.savePlace(place);
assertEquals(1, tournament.getPlaces().size());
try {
tournament.removePlace(place);
assertEquals(0, tournament.getPlaces().size());
} catch (Tournament.PlaceNotExistsException e) {
fail();
}
}
@Test
@DisplayName("Test gameschedule calculation")
void calcGameSchedule() {
Participant participant = mock(Player.class);
when(participant.equals(any(Participant.class))).thenReturn(false);
//Checks if invalid number of Participants throws error
assertThrows(Tournament.NumberOfParticipantInvalidException.class, () -> tournament.createGameSchedule());
for (int i = 0; i < 8; i++) {
if (i % 4 == 0 && i > 0) {
try {
tournament.createGameSchedule();
assertEquals(2, tournament.getGameList().size());
tournament.saveParticipant(participant);
} catch (Tournament.NumberOfParticipantInvalidException e) {
fail();
}
} else {
assertThrows(Tournament.NumberOfParticipantInvalidException.class, () -> tournament.createGameSchedule());
tournament.saveParticipant(participant);
}
}
try {
tournament.createGameSchedule();
} catch (Tournament.NumberOfParticipantInvalidException e) {
fail();
}
assertEquals(3, tournament.getGameList().size());
}
}
}