Initial commit

This commit is contained in:
github-classroom[bot] 2022-04-27 10:00:50 +00:00
commit bd1d2e051c
40 changed files with 5271 additions and 0 deletions

29
.editorconfig Normal file
View File

@ -0,0 +1,29 @@
# EditorConfig is awesome: https://EditorConfig.org
# top-most EditorConfig file
root = true
# Default formatting Unix-style newlines with a newline ending every file
[*]
charset = utf-8
end_of_line = lf
insert_final_newline = true
trim_trailing_whitespace = true
indent_style = space
indent_size = 4
# do not trim trailing whitespace in markdown files
[*.md]
trim_trailing_whitespace = false
# explicit 4 space indentation
[*.py]
indent_size = 4
# explicit 2 space indentation
[*.{json, yml, yaml, xml, ddl, sql}]
indent_size = 2
# windows specific files
[*.{bat, cmd}]
end_of_line = crlf

5
.gitattributes vendored Normal file
View File

@ -0,0 +1,5 @@
#
# https://help.github.com/articles/dealing-with-line-endings/
#
# These are explicitly windows files and should use crlf
*.bat text eol=crlf

14
.github/classroom/autograding.json vendored Normal file
View File

@ -0,0 +1,14 @@
{
"tests": [
{
"name": "Run PA unit tests",
"setup": "",
"run": "gradle :Herzschlag:autograding --info",
"input": "",
"output": "",
"comparison": "included",
"timeout": 10,
"points": 2
}
]
}

15
.github/workflows/classroom.yml vendored Normal file
View File

@ -0,0 +1,15 @@
name: GitHub Classroom Workflow
on: [push]
jobs:
build:
name: Autograding
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Set up JDK 17
uses: actions/setup-java@v1
with:
java-version: '17'
- uses: education/autograding@v1

70
.gitignore vendored Normal file
View File

@ -0,0 +1,70 @@
# InelliJ IDEA files
*.iml
*.ipr
*.ids
*.iws
.idea/
# Eclipse files
.project
.metadata
.classpath
.settings/
.loadpath
bin/
# Netbeans
nbactions.xml
# Visual Studio Code
.vscode
# Maven
target/
# gradle files
.gradle
build/
# ignore logfiles
*.log*
# OS dependant files
.DS_Store
.Spotlight-V100
.Trashes
Thumbs.db
Desktop.ini
*~
# Thumbnails
._*
# compiled files
*.com
*.class
*.dll
*.exe
*.o
*.so
# packages
*.7z
#*.jar
*.rar
*.zip
*.gz
*.bzip
*.xz
*.lzma
*~$*
# package managment formats
*.dmg
*.xpi
*.gem
*.egg
*.deb
*.rpm
# databases
*.sqlite

210
README.adoc Normal file
View File

@ -0,0 +1,210 @@
:source-highlighter: coderay
:icons: font
:experimental:
:!sectnums:
:imagesdir: ./images/
:handout: ./code/
:logo: IT.PROG2 -
ifdef::backend-html5[]
:logo: image:PROG2-300x300.png[IT.PROG2,100,100,role=right,fit=none,position=top right]
endif::[]
ifdef::backend-pdf[]
:logo:
endif::[]
ifdef::env-github[]
:tip-caption: :bulb:
:note-caption: :information_source:
:important-caption: :heavy_exclamation_mark:
:caution-caption: :fire:
:warning-caption: :warning:
endif::[]
// references
:mockito-home: http://mockito.org/[Mockito Homepage]
:mockito-docs: http://mockito.github.io/mockito/docs/current/org/mockito/Mockito.html[Mockito Dokumentation]
:mockito-annotations: https://www.baeldung.com/mockito-annotations[Konkrete Beispiele mit Mockito]
:planet-wissen-herz: https://www.planet-wissen.de/video-das-herz--wie-funktioniert-es-100.html[Planet Wissen]
:maven-central: https://search.maven.org/search?q=a:mockito-core[MavenCentral]
= {logo} Praktikum Mock-Testing
== Einleitung
Ziele dieses Praktikums sind:
* Anwenden von erweiterten Testverfahren (Mocks, Spys)
* Übung des Umgangs mit Mockito
=== Voraussetzungen
* Vorlesung Mock-Testing
=== Tooling
* Installiertes JDK 17+.
* Gradle 7.4+
* Mockito ab Version 2.
=== Struktur
Das Praktikum enthält verschiedene Arten von Aufgaben, die wie folgt gekennzeichnet sind:
[TU] Theoretische Übung::
Dient der Repetition bzw. Vertiefung des Stoffes aus der Vorlesung und als Vorbereitung für die nachfolgenden Übungen.
[PU] Praktische Übung::
Übungsaufgaben zur praktischen Vertiefung von Teilaspekten des behandelten Themas.
[PA] Pflichtaufgabe::
Übergreifende Aufgabe zum Abschluss. Das Lösen dieser Aufgaben ist Pflicht. Sie muss bis zum definierten Zeitpunkt abgegeben werden, wird bewertet und ist Teil der Vornote.
=== Zeit und Bewertung
Für das Praktikum stehen zwei Wochen in den Praktikumslektionen und im Selbststudium zur Verfügung.
Je nach Kenntniss- und Erfahrungsstufe benötigen Sie mehr oder weniger Zeit.
Nutzen Sie die Gelegenheit, den Stoff zu vertiefen, auszuprobieren, Fragen zu stellen und Lösungen zu diskutieren (Intensive-Track).
Falls Sie das Thema schon beherrschen, müssen Sie nur die Pflichtaufgaben lösen und bis zum angegebenen Zeitpunkt abgeben (Fast-Track).
Sie können die Lösungen der Textaufgaben in diesem Praktikum direkt in den Java-Files als Kommentar hinzufügen - oder als Markdown-File neben den Java-Files.
=== Referenzen
* link:{handout}[Praktikumsverzeichnis Quellcode, Projektstruktur]
* link:{mockito-home}
* link:{mockito-docs}
* link:{mockito-annotations}
:sectnums:
:sectnumlevels: 2
// Beginn des Aufgabenblocks
== Herz
Das menschliche Herz ist ein lebenswichtiges und kompliziertes Organ.
Nur, wenn seine einzelnen "Bauteile" richtig koordiniert werden, kann es eine ausreichende Blutversorgung unseres Körpers gewährleisten.
Da es beim Mocking um das Testen des Verhaltens eines Objekts geht, bietet sich das Herz als Beispiel an.
Darum simulieren wir in dieser Aufgabe ein menschliches Herz.
Eine kurze Erklärung der Funktionsweise des Herzens gibt es auf link:{planet-wissen-herz}.
Einige Fakten über das Herz, die bei dieser Aufgabe helfen können -
im Projekt werden englische Begriffe verwendet, die Sie in Klammern finden:
* Das Herz (Heart) besteht aus zwei Hälften.
* Jede Herzhälfte (Half) hat einen Vorhof (Atrium) und eine Herzkammer (Ventricle).
Vorhöfe sammeln Blut, Herzkammern pressen es in den Körper.
* Zwei Phasen wechseln sich jeweils ab.
** Anspannungsphase: Systole
** Entspannungsphase: Diastole
* Die Herzklappen sind eine Art Rücklaufventile, es gibt 2 verschiedene:
** 2 Segelklappen (AtrioventricularValve): verhindern, dass Blut in der Systole in den Vorhof zurückfliesst.
** 2 Taschenklappen (SemilunarValve): verhindern, dass in der Diastole Blut ins Herz zurückfliesst.
image:Heart_diagram-en.svg.png[pdfwidth=75%, width=600px]
=== Ablauf des Herzschlags
==== Diastole Blut sammelt sich im Vorhof ("atrium")
* Segelklappen ("atrioventricular valves") öffnen
* Taschenklappen ("semilunar valves") schliessen
* Vorhöfe ("atria") entspannen
* Herzkammern ("ventricle") entspannen
* Warten auf Systole
==== Systole
* Segelklappen schliessen
* Taschenklappen öffnen
* Herzkammern kontrahieren
* Vorhöfe kontrahieren
* Warten auf Diastole
Es gibt die folgenden Klassen im Projekt:
image:heartbeat_classdiagram.png[pdfwidth=75%, width=600px]
Darüber hinaus gibt es eine Klasse `HeartTest`, die bereits mehrere Tests implementiert.
Stubs sind nicht sehr intelligent und daher kann man häufig nur oberflächlich mit Stubs testen.
Sie sollen mit Hilfe von Mock-Objekten die Tests noch gründlicher gestalten.
Die Abhängigkeit für Mockito ist bereits für Sie in build.gradle erfasst worden.
Studieren Sie kurz in diesem File, wie das gemacht wurde.
Informationen dazu finden Sie auf der link:{mockito-home} und auf link:{maven-central}.
Studieren bzw. überfliegen Sie bei dieser Gelegenheit auch gerade die link:{mockito-docs}.
== Aufgaben
=== Einführung in Mockito [PU]
[loweralpha]
. Studieren Sie die Testmethoden `HeartTest::testValveStatus()` und `HeartTest::testExecuteHartBeatErrorBehaviour()`.
Dort wird *ein Teil* des Verhaltens des Herzens getestet.
. Implementieren Sie die Methoden `Heart::executeDiastole()`, `Heart::executeSystole()` und `Heart::executeHeartBeat()` sodass die bestehenden Tests durchlaufen und das oben beschriebene Verhalten des Herzens modelliert wird.
. (optional) Ein echtes Herz hat eine Schlagfrequenz.
Implementieren Sie, dass das Herz nach jeder Systole pausiert.
Sie können z. B. den aktuellen Thread 1000 ms lang anhalten mit
+
[source, Java]
----
try {
Thread.currentThread().sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
----
=== Fragen zu Testing [TU]
[loweralpha]
. Testing kann in zwei unterschiedliche Strategien aufgeteilt werden.
Zum einen gibt es White-Box Testing und zum zweiten Black-Box Testing.
Was für Java Libraries gibt es um diese zwei Strategien zu testen?
Wann wenden Sie welche Strategie an?
. Das Erstellen von guten automatisierten Unit-Tests kann manchmal schwierig umzusetzen sein.
Was ist der Hauptgrund dafür? Wie können Sie dieses Problem entschärfen?
. Der Testfokus war bisher auf der Klasse `Heart`.
Testen Sie jetzt die Klasse `Half`. Wo verwenden Sie Stubbing, wo Mocking?
=== Vorbedingungen, Exceptions und Callback-Funktionen [PA]
[loweralpha]
. Testen Sie, dass beim Ausführen der Diastole und Systole alle Herzklappen in der richtigen Reihenfolge geöffnet und geschlossen werden.
Implementieren Sie dafür die Methode `HeartTest::testValvesBehavior()` und benutzen Sie die von Mockito bereitgestellte Klasse `InOrder`. +
Testen Sie auch, dass keine Methode unnötig oft aufgerufen wird (mit der Methode `Inorder::verifyNoMoreInteractions()`). +
Benutzen Sie mindestens einmal die statische Methode `mock()` und einmal die Annotation `@Mock` von Mockito.
. Die vorhandene Implementation des Testfalls `HeartTest::testExecuteHartBeatErrorBehaviour()` verwendet keine Mock-Objekte für die linke und rechte Herzhälfte.
Implementieren Sie die Testmethode `HeartTest::testExecuteHartBeatErrorBehaviourWithStubbing()` analog zur bestehenden Variante, aber diesmal setzen Sie entsprechende Mock-Objekte für die Herzhälften ein.
+
TIP: Für das Stubbing werden Sie die `doThrow`- Methode von Mockito benötigen.
Mit Stubbing ist die Konfiguration von Ihrem Mock-Objekt gemeint.
. Die bestehende Implementierung hat einen ungenügenden Exception-Mechanismus.
Beispielsweise führt die Herzhälfte (`Half`) ihre Methoden aus, auch wenn die notwendigen Vorbedingungen (d.h., die Klappenstellungen von `SemilunarValve` und `AtrioVentricularValve`)
nicht gelten. +
Beheben Sie dieses Problem, indem Sie in `Heart::executeDiastole()` und `Heart::executeSystole()` eine `InvalidValvePositionException` werfen,
falls die notwendigen Vorbedingungen nicht in der korrekten Position (offen, geschlossen) sind. +
Erstellen Sie zwei Methoden `testDiastoleException()` und `testSystoleException()` und setzen Sie Mocking und Stubbing ein, um diesen Exception-Mechanismus zu testen.
. Die Klasse Pacemaker ist eine Implementation für einen Herzschrittmacher.
Es ist eine unvollständige Implementation, reduziert auf das Wesentliche für den Inhalt des Praktikums.
Ihre Aufgabe ist es, die Methode `Pacemaker::setHeartRate` mit zwei vorgegeben Testfällen zu testen. +
Implementieren Sie Test-Methoden `PacemakerTest::testSetHeartRateRejectsFrequenciesOutOfRange` und `PacemakerTest::testSetHeartRateAppliesFrequenciesInsideRange`. +
Die beiden Testfälle prüfen die Methode `Pacemaker::setHeartRate` darauf, ob sie korrekt reagiert, wenn das Herz die gewünschte Frequenz im einen Fall anwenden und im anderen Fall nicht anwenden kann.
In diesem Szenario ist die Klasse `Pacemaker` die Class-Under-Test und die Klasse `Heart` eine Abhängigkeit für `Pacemaker`. +
Verwenden Sie für die Klasse `Heart` ein entsprechendes Mock-Objekt und stubben Sie das Verhalten gemäss der Spezifikation von der Methode `Heart::setHeartRate()`.
Eine Voraussetzung ist, dass Sie für beide Testfälle dasselbe Mock-Objekt mit demselben Stubbing verwenden können.
Die Callback-Methode wird Ihnen dabei eine Hilfe sein.
== Abschluss
Stellen Sie sicher, dass die Tests der Pflichtaufgabe mittels `gradlew test` gestartet werden können und pushen Sie die Lösung vor der Deadline in Ihr Abgaberepository.

View File

@ -0,0 +1,74 @@
/*
* This file was generated by the Gradle 'init' task.
*
* This generated file contains a sample Java application project to get you started.
* For more details take a look at the 'Building Java & JVM projects' chapter in the Gradle
* User Manual available at https://docs.gradle.org/7.2/userguide/building_java_projects.html
*/
plugins {
// Apply the application plugin to add support for building a CLI application in Java.
id 'application'
}
repositories {
// Use Maven Central for resolving dependencies.
mavenCentral()
}
dependencies {
// Junit 5 dependencies
testImplementation 'org.junit.jupiter:junit-jupiter-api:5.8.+'
testImplementation 'org.junit.jupiter:junit-jupiter-params:5.8.+'
testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.8.+'
// Mockito dependencies
testImplementation 'org.mockito:mockito-core:4.3.+'
}
// Test task configuration
test {
// Use JUnit platform for unit tests
useJUnitPlatform()
// Output results of individual tests
testLogging {
events "PASSED", "SKIPPED", "FAILED"
}
}
application {
// Define the main class for the application.
mainClass = 'ch.zhaw.prog2.heartbeat.Heart'
}
// Java plugin configuration
java {
// By default the Java version of the gradle process is used as source/target version.
// This can be overridden, to ensure a specific version. Enable only if required.
// sourceCompatibility = JavaVersion.VERSION_17 // ensure Java source code compatibility
// targetCompatibility = JavaVersion.VERSION_17 // version of the created byte-code
// Java compiler specific options
compileJava {
// source files should be UTF-8 encoded
options.encoding = 'UTF-8'
// for more options see https://docs.gradle.org/current/dsl/org.gradle.api.tasks.compile.CompileOptions.html
}
}
task autograding(type: Test) {
description = "Runs specific tests for autograding"
group = 'verification'
useJUnitPlatform()
testLogging {
events "PASSED", "SKIPPED", "FAILED"
}
filter {
failOnNoMatchingTests true
includeTestsMatching "PacemakerTest"
includeTestsMatching "HeartTest.testExecuteHartBeatErrorBehaviourWithStubbing"
includeTestsMatching "HeartTest.testValvesBehavior"
includeTestsMatching "HeartTest.testDiastoleException"
includeTestsMatching "HeartTest.testSystoleException"
}
}

View File

@ -0,0 +1,100 @@
package ch.zhaw.prog2.heartbeat;
import ch.zhaw.prog2.heartbeat.parts.*;
/**
* Represents one half of a heart.
*
* @author wahl, muon
*/
public class Half {
public enum Side {LEFT, RIGHT}
private Atrium atrium; // "Vorhof"
private Ventricle ventricle; // "Herzkammer"
private AtrioventricularValve atrioventricularValve; // "Segelklappe"
private SemilunarValve semilunarValve; // "Taschenklappe"
private final Side side;
public Half(Side side) {
this.side = side;
atrium = new Atrium(side);
ventricle = new Ventricle(side);
atrioventricularValve = new AtrioventricularValve(side);
semilunarValve = new SemilunarValve(side);
}
public void initializeState(Heart.State state) {
atrioventricularValve.initializeState(state);
semilunarValve.initializeState(state);
}
public AtrioventricularValve getAtrioventricularValve() {
return atrioventricularValve;
}
public SemilunarValve getSemilunarValve() {
return semilunarValve;
}
public boolean isAtrioventricularValveOpen() {
return atrioventricularValve.isOpen();
}
public boolean isSemilunarValveOpen() {
return semilunarValve.isOpen();
}
/**
* Closes the valve
*
* @throws IllegalStateException when valve is already closed
*/
public void closeSemilunarValve() throws Valve.IllegalValveStateException {
semilunarValve.close();
}
/**
* Opens the valve
*
* @throws Valve.IllegalValveStateException when the valve is already open
*/
public void openSemilunarValve() throws Valve.IllegalValveStateException {
semilunarValve.open();
}
/**
* Closes the valve
*
* @throws Valve.IllegalValveStateException when valve is already closed
*/
public void closeAtrioventricularValve() throws Valve.IllegalValveStateException {
atrioventricularValve.close();
}
/**
* Opens the valve
*
* @throws Valve.IllegalValveStateException when the valve is already open
*/
public void openAtrioventricularValve() throws Valve.IllegalValveStateException {
atrioventricularValve.open();
}
public void contractVentricle() {
ventricle.contract();
}
public void relaxVentricle() {
ventricle.relax();
}
public void contractAtrium() {
atrium.contract();
}
public void relaxAtrium() {
atrium.relax();
}
}

View File

@ -0,0 +1,145 @@
package ch.zhaw.prog2.heartbeat;
import ch.zhaw.prog2.heartbeat.parts.Valve;
import java.util.ArrayList;
import java.util.List;
/**
* This class represents a human heart (https://en.wikipedia.org/wiki/Heart).
* <p>
* <p>
* Example tests: before Chamber::contract() is called, the atrioventricular
* valves must be closed.
*
* @author wahl
*/
public class Heart {
private final static int AVERAGE_HEART_RATE = 60;
/**
* Encodes the states of the heart
*
* @author wahl
*/
public enum State {
SYSTOLE, DIASTOLE
}
private List<Half> halves;
private State state;
private int heartRate;
/**
* The default constructor calls the more specific constructor with a new left
* and right half.
*/
public Heart() {
this(new Half(Half.Side.LEFT), new Half(Half.Side.RIGHT));
}
/**
* The default constructor adds the left and the right half that are specified
* as parameters and sets the start state to diastole.
*/
public Heart(Half leftHalf, Half rightHalf) {
state = State.DIASTOLE;
heartRate = AVERAGE_HEART_RATE;
halves = new ArrayList<>();
halves.add(leftHalf);
halves.add(rightHalf);
initalizeState();
}
public void initalizeState(){
for(Half half : halves){
half.initializeState(state);
}
}
/**
* Executes a sequence of diastole and systole, beginning with the current
* state.
*
* @throws HeartBeatDysfunctionException when Valve.IllegalValveStateException or
* InvalidValvePositionException occurs during diastole or systole
* TODO Implement a pause mechanism based on the current heart rate
*/
public void executeHeartBeat() throws HeartBeatDysfunctionException{
//TODO implement
}
/**
* Executes the diastole phase of the heart.
*
* @throws Valve.IllegalValveStateException when one of the valves has an illegal State
*/
public void executeDiastole() {
//TODO implement
}
/**
* Executes the systole phase of the heart.
*
* @throws Valve.IllegalValveStateException when one of the valves has an illegal State
*/
public void executeSystole() {
//TODO implement
}
public State getState() {
return state;
}
public void setState(State state) {
this.state = state;
}
/**
* Sets the heart rate to the parameter value in Hz.
* Rate has to be inside range >30 && <220
* If rate is outside of range method rejects the change
* and returns false.
*
* @param frequencyInHz which should be applied to the heart
* @return true if the heart rate could be set, false otherwise
*/
public boolean setHeartRate(int frequencyInHz) {
if (frequencyInHz < 30 || frequencyInHz > 220) {
return false;
}
this.heartRate = frequencyInHz;
return true;
}
public int getHeartRate() {
return heartRate;
}
public List<Half> getHalves() {
return halves;
}
public static class HeartBeatDysfunctionException extends Exception {
public HeartBeatDysfunctionException() {
}
public HeartBeatDysfunctionException(String message) {
super(message);
}
public HeartBeatDysfunctionException(String message, Throwable cause) {
super(message, cause);
}
}
/**
* The main method instantiates a heart object and executes a single heartbeat.
*
* @param args
*/
public static void main(String[] args) throws HeartBeatDysfunctionException {
Heart heart = new Heart();
heart.executeHeartBeat();
}
}

View File

@ -0,0 +1,44 @@
package ch.zhaw.prog2.heartbeat;
/**
* This class represents a pacemaker for a human hart.
*
* This is an incomplete implementation, reduced to the essentials for the content of the lab.
* There would be a lot more code needed to implement a pacemaker, but this is not part of this lab :-)
*
* @author muon
*
*/
public class Pacemaker {
Heart heart;
/**
* Constructor of Pacemaker
* @param heart
*/
public Pacemaker(Heart heart) {
this.heart = heart;
}
/**
* Sets the heart rate to the parameter value in Hz.
* Rate has to be inside range >30 && <220
* If frequency can be applied on heart, the current frequency will be returned.
* If heart does reject the change the method throws an exception.
*
* @param frequencyInHz needs to be applied on heart
* @return current frequency of the heart
* @throws IllegalArgumentException when heart does reject the change
*/
public int setHeartRate(int frequencyInHz) {
if(heart.setHeartRate(frequencyInHz) == false){
throw new IllegalArgumentException("Frequency could not be set.");
}
return heart.getHeartRate();
}
/*
...
There would be a lot more code needed to implement a pacemaker, but this is not part of this lab :-)
...
*/
}

View File

@ -0,0 +1,19 @@
package ch.zhaw.prog2.heartbeat.parts;
import ch.zhaw.prog2.heartbeat.Half.Side;
import ch.zhaw.prog2.heartbeat.Heart;
public class AtrioventricularValve extends Valve {
public AtrioventricularValve(Side side) {
super (side);
}
public void initializeState(Heart.State state) {
if(Heart.State.DIASTOLE.equals(state)){
setOpen(false);
}else{
setOpen(true);
}
}
}

View File

@ -0,0 +1,20 @@
package ch.zhaw.prog2.heartbeat.parts;
import ch.zhaw.prog2.heartbeat.Half.Side;
public class Atrium {
private Side side;
public Atrium (Side side) {
this.side = side;
}
public void contract() {
System.out.println("Atrium "+ side + " is contracting.");
}
public void relax() {
System.out.println("Atrium "+ side + " is relaxing.");
}
}

View File

@ -0,0 +1,20 @@
package ch.zhaw.prog2.heartbeat.parts;
import ch.zhaw.prog2.heartbeat.Half.Side;
import ch.zhaw.prog2.heartbeat.Heart;
public class SemilunarValve extends Valve {
public SemilunarValve(Side side) {
super (side);
}
public void initializeState(Heart.State state) {
if(Heart.State.DIASTOLE.equals(state)){
setOpen(true);
}else{
setOpen(false);
}
}
}

View File

@ -0,0 +1,61 @@
package ch.zhaw.prog2.heartbeat.parts;
import ch.zhaw.prog2.heartbeat.Half.Side;
public abstract class Valve {
private boolean open;
private Side side;
public Valve(Side side) {
this.side = side;
}
/**
* Opens the valve
*
* @throws IllegalValveStateException when the valve is already open
*/
public void open() throws IllegalValveStateException {
if (open) {
throw new IllegalValveStateException(this.getClass().getSimpleName() + " " + side + " valve is already open.");
}
System.out.println(this.getClass().getSimpleName() + " " + side + " is opening.");
open = true;
}
/**
* Closes the valve
*
* @throws IllegalValveStateException when valve is already closed
*/
public void close() throws IllegalValveStateException {
if (!open) {
throw new IllegalValveStateException(this.getClass().getSimpleName() + " " + side + " valve is already closed.");
}
System.out.println(this.getClass().getSimpleName() + " " + side + " is closing.");
open = false;
}
public boolean isOpen() {
return open;
}
protected void setOpen(Boolean open) {
this.open = open;
}
public static class IllegalValveStateException extends Exception {
public IllegalValveStateException() {
}
public IllegalValveStateException(String message) {
super(message);
}
public IllegalValveStateException(String message, Throwable cause) {
super(message, cause);
}
}
}

View File

@ -0,0 +1,20 @@
package ch.zhaw.prog2.heartbeat.parts;
import ch.zhaw.prog2.heartbeat.Half.Side;
public class Ventricle {
private Side side;
public Ventricle (Side side) {
this.side = side;
}
public void contract() {
System.out.println("Chamber "+ side + " is contracting.");
}
public void relax() {
System.out.println("Chamber "+ side + " is relaxing.");
}
}

View File

@ -0,0 +1,100 @@
/*
* Test Class for Heart
*/
package ch.zhaw.prog2.heartbeat;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
import ch.zhaw.prog2.heartbeat.parts.Valve;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import ch.zhaw.prog2.heartbeat.Heart.State;
class HeartTest {
/**
* This is a very simple test to check if Junit and Mockito are properly set up.
*/
@Test
void testTheTest() {
Heart classUnderTest = new Heart();
assertNotNull(classUnderTest.getState(), "The heart must have a state.");
}
/**
* Tests a single heartbeat
*/
@Test
void testHeartBeat() throws Heart.HeartBeatDysfunctionException {
Heart heart = new Heart();
State startState = heart.getState();
heart.executeHeartBeat();
// after one heartbeat, the heart must be in the same state as before
assertEquals(startState, heart.getState());
}
/**
* Tests if the valves are open or closed depending on the status of the heart
*/
@Test
void testValveStatus() throws Heart.HeartBeatDysfunctionException {
Heart heart = new Heart();
heart.executeHeartBeat();
State state = heart.getState();
if (state.equals(Heart.State.DIASTOLE)) {
for (Half half : heart.getHalves()) {
assertFalse(half.isAtrioventricularValveOpen());
assertTrue(half.isSemilunarValveOpen());
}
} else if ((state.equals(Heart.State.SYSTOLE))) {
for (Half half : heart.getHalves()) {
assertTrue(half.isAtrioventricularValveOpen());
assertFalse(half.isSemilunarValveOpen());
}
}
}
/**
* Tests if the hart throws the appropriate Exception, when malfunction was detected during hartBeat
*/
@Test
void testExecuteHeartBeatErrorBehaviour() {
Heart heart = new Heart();
// prepare error situation due to wrong initialization
heart.setState(State.SYSTOLE);
assertThrows(Heart.HeartBeatDysfunctionException .class, // verification using lambda
() -> heart.executeHeartBeat());
}
/**
* Tests if the hart throws the appropriate Exception, when malfunction was detected during hartBeat
* with exception Stubbing
*/
@Test
void testExecuteHartBeatErrorBehaviourWithStubbing() throws Valve.IllegalValveStateException {
//TODO implement
fail();
}
/**
* We test if Heart::executeHeartbeat() sends the right signals to both of its
* halves.
*
* When Half::contractVentricle() is called, Half::closeAtrioventricularValve()
* and Half::openSemilunarValve() must have been called earlier.
*
*/
@Test
void testValvesBehavior() {
//TODO implement
fail();
}
}

View File

@ -0,0 +1,30 @@
package ch.zhaw.prog2.heartbeat;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
/*
* Test Class for Pacemaker
*/
public class PacemakerTest {
/**
* Test if setHeartRate does throw correct exception when rate is rejected (because frequency is out of range)
*/
@Test
void testSetHeartRateRejectsFrequenciesOutOfRange() {
//TODO implement
fail();
}
/**
* Test if setHeartRate does correctly set the rate when frequency is inside range
*/
@Test
void testSetHeartRateAppliesFrequenciesInsideRange() {
//TODO implement
fail();
}
}

7
gradle.properties Normal file
View File

@ -0,0 +1,7 @@
# Used to set properties for gradle builds
# (see https://dev.to/jmfayard/configuring-gradle-with-gradle-properties-211k)
# gradle configuration
# (https://docs.gradle.org/current/userguide/build_environment.html#sec:gradle_configuration_properties)
#org.gradle.warning.mode=(all,fail,summary,none) default: summary
org.gradle.warning.mode=all

BIN
gradle/wrapper/gradle-wrapper.jar vendored Normal file

Binary file not shown.

View File

@ -0,0 +1,5 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-7.4-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

234
gradlew vendored Executable file
View File

@ -0,0 +1,234 @@
#!/bin/sh
#
# Copyright © 2015-2021 the original authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
##############################################################################
#
# Gradle start up script for POSIX generated by Gradle.
#
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
app_path=$0
# Need this for daisy-chained symlinks.
while
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
[ -h "$app_path" ]
do
ls=$( ls -ld "$app_path" )
link=${ls#*' -> '}
case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done
APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
APP_NAME="Gradle"
APP_BASE_NAME=${0##*/}
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
warn () {
echo "$*"
} >&2
die () {
echo
echo "$*"
echo
exit 1
} >&2
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "$( uname )" in #(
CYGWIN* ) cygwin=true ;; #(
Darwin* ) darwin=true ;; #(
MSYS* | MINGW* ) msys=true ;; #(
NONSTOP* ) nonstop=true ;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD=$JAVA_HOME/jre/sh/java
else
JAVACMD=$JAVA_HOME/bin/java
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD=java
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
fi
# Collect all arguments for the java command, stacking in reverse order:
# * args from the command line
# * the main class name
# * -classpath
# * -D...appname settings
# * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi
# Collect all arguments for the java command;
# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of
# shell script including quotes and variable substitutions, so put them in
# double quotes to make sure that they get re-expanded; and
# * put everything else in single quotes, so that it's not re-expanded.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-classpath "$CLASSPATH" \
org.gradle.wrapper.GradleWrapperMain \
"$@"
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@"

89
gradlew.bat vendored Normal file
View File

@ -0,0 +1,89 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto execute
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega

Binary file not shown.

After

Width:  |  Height:  |  Size: 378 KiB

BIN
images/PROG2-300x300.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 121 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 91 KiB

45
settings.gradle Normal file
View File

@ -0,0 +1,45 @@
/*
* Dynamic Multi-Module project structure
* automatically adds each exercise as a sub-project (module)
*/
// use current directory name as root project name
rootProject.name = file('.').name
// dynamically add sub-projects in handout folder
File handoutDir = file('code')
if (handoutDir.isDirectory()) {
handoutDir.eachDir { dir ->
String subProjectName = ":${dir.name}"
include(subProjectName)
project(subProjectName).projectDir = dir
}
}
// dynamically add sub-projects in solutions* folders
//List<File> solutionDirs = List.of(file('.').listFiles((File dir, String name) -> name.startsWith("solutions")))
file('.').eachDirMatch( name -> name.startsWith('solutions')) { solutionDir ->
if (solutionDir.isDirectory()) {
solutionDir.eachDir { dir ->
if (!dir.name.equals('images')) {
String subProjectName = ":${dir.name}-sol"
include(subProjectName)
project(subProjectName).projectDir = dir
}
}
}
}
// lab preparation tasks
File classroomDir = file('classroom')
if (classroomDir.isDirectory()) {
String subProjectName = ":${classroomDir.name}"
include(subProjectName)
}
// Example: manually adding sub-project with name == folder
//include 'module1'
// Example: manually adding sub-projects with different name & folder
//include(':lab00-module1')
//project(':lab00-module1').projectDir = file('handout/module1')

View File

@ -0,0 +1,74 @@
/*
* This file was generated by the Gradle 'init' task.
*
* This generated file contains a sample Java application project to get you started.
* For more details take a look at the 'Building Java & JVM projects' chapter in the Gradle
* User Manual available at https://docs.gradle.org/7.2/userguide/building_java_projects.html
*/
plugins {
// Apply the application plugin to add support for building a CLI application in Java.
id 'application'
}
repositories {
// Use Maven Central for resolving dependencies.
mavenCentral()
}
dependencies {
// Junit 5 dependencies
testImplementation 'org.junit.jupiter:junit-jupiter-api:5.8.+'
testImplementation 'org.junit.jupiter:junit-jupiter-params:5.8.+'
testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.8.+'
// Mockito dependencies
testImplementation 'org.mockito:mockito-core:4.3.+'
}
// Test task configuration
test {
// Use JUnit platform for unit tests
useJUnitPlatform()
// Output results of individual tests
testLogging {
events "PASSED", "SKIPPED", "FAILED"
}
}
application {
// Define the main class for the application.
mainClass = 'ch.zhaw.prog2.heartbeat.Heart'
}
// Java plugin configuration
java {
// By default the Java version of the gradle process is used as source/target version.
// This can be overridden, to ensure a specific version. Enable only if required.
// sourceCompatibility = JavaVersion.VERSION_17 // ensure Java source code compatibility
// targetCompatibility = JavaVersion.VERSION_17 // version of the created byte-code
// Java compiler specific options
compileJava {
// source files should be UTF-8 encoded
options.encoding = 'UTF-8'
// for more options see https://docs.gradle.org/current/dsl/org.gradle.api.tasks.compile.CompileOptions.html
}
}
task autograding(type: Test) {
description = "Runs specific tests for autograding"
group = 'verification'
useJUnitPlatform()
testLogging {
events "PASSED", "SKIPPED", "FAILED"
}
filter {
failOnNoMatchingTests true
includeTestsMatching "PacemakerTest"
includeTestsMatching "HeartTest.testExecuteHartBeatErrorBehaviourWithStubbing"
includeTestsMatching "HeartTest.testValvesBehavior"
includeTestsMatching "HeartTest.testDiastoleException"
includeTestsMatching "HeartTest.testSystoleException"
}
}

View File

@ -0,0 +1,100 @@
package ch.zhaw.prog2.heartbeat;
import ch.zhaw.prog2.heartbeat.parts.*;
/**
* Represents one half of a heart.
*
* @author wahl, muon
*/
public class Half {
public enum Side {LEFT, RIGHT}
private Atrium atrium; // "Vorhof"
private Ventricle ventricle; // "Herzkammer"
private AtrioventricularValve atrioventricularValve; // "Segelklappe"
private SemilunarValve semilunarValve; // "Taschenklappe"
private final Side side;
public Half(Side side) {
this.side = side;
atrium = new Atrium(side);
ventricle = new Ventricle(side);
atrioventricularValve = new AtrioventricularValve(side);
semilunarValve = new SemilunarValve(side);
}
public void initializeState(Heart.State state) {
atrioventricularValve.initializeState(state);
semilunarValve.initializeState(state);
}
public AtrioventricularValve getAtrioventricularValve() {
return atrioventricularValve;
}
public SemilunarValve getSemilunarValve() {
return semilunarValve;
}
public boolean isAtrioventricularValveOpen() {
return atrioventricularValve.isOpen();
}
public boolean isSemilunarValveOpen() {
return semilunarValve.isOpen();
}
/**
* Closes the valve
*
* @throws IllegalStateException when valve is already closed
*/
public void closeSemilunarValve() throws Valve.IllegalValveStateException {
semilunarValve.close();
}
/**
* Opens the valve
*
* @throws Valve.IllegalValveStateException when the valve is already open
*/
public void openSemilunarValve() throws Valve.IllegalValveStateException {
semilunarValve.open();
}
/**
* Closes the valve
*
* @throws Valve.IllegalValveStateException when valve is already closed
*/
public void closeAtrioventricularValve() throws Valve.IllegalValveStateException {
atrioventricularValve.close();
}
/**
* Opens the valve
*
* @throws Valve.IllegalValveStateException when the valve is already open
*/
public void openAtrioventricularValve() throws Valve.IllegalValveStateException {
atrioventricularValve.open();
}
public void contractVentricle() {
ventricle.contract();
}
public void relaxVentricle() {
ventricle.relax();
}
public void contractAtrium() {
atrium.contract();
}
public void relaxAtrium() {
atrium.relax();
}
}

View File

@ -0,0 +1,168 @@
package ch.zhaw.prog2.heartbeat;
import ch.zhaw.prog2.heartbeat.parts.Valve;
import java.util.ArrayList;
import java.util.List;
/**
* This class represents a human heart (https://en.wikipedia.org/wiki/Heart).
* <p>
* <p>
* Example tests: before Chamber::contract() is called, the atrioventricular
* valves must be closed.
*
* @author wahl
*/
public class Heart {
private final static int AVERAGE_HEART_RATE = 60;
/**
* Encodes the states of the heart
*
* @author wahl
*/
public enum State {
SYSTOLE, DIASTOLE
}
private List<Half> halves;
private State state;
private int heartRate;
/**
* The default constructor calls the more specific constructor with a new left
* and right half.
*/
public Heart() {
this(new Half(Half.Side.LEFT), new Half(Half.Side.RIGHT));
}
/**
* The default constructor adds the left and the right half that are specified
* as parameters and sets the start state to diastole.
*/
public Heart(Half leftHalf, Half rightHalf) {
state = State.DIASTOLE;
heartRate = AVERAGE_HEART_RATE;
halves = new ArrayList<>();
halves.add(leftHalf);
halves.add(rightHalf);
initalizeState();
}
public void initalizeState(){
for(Half half : halves){
half.initializeState(state);
}
}
/**
* Executes a sequence of diastole and systole, beginning with the current
* state.
*
* @throws HeartBeatDysfunctionException when Valve.IllegalValveStateException or
* InvalidValvePositionException occurs during diastole or systole
* TODO Implement a pause mechanism based on the current heart rate
*/
public void executeHeartBeat() throws HeartBeatDysfunctionException {
try {
if (state.equals(State.DIASTOLE)) {
executeDiastole();
executeSystole();
} else {
executeSystole();
executeDiastole();
}
} catch (Valve.IllegalValveStateException | InvalidValvePositionException e) {
System.out.println(e.getMessage());
throw new HeartBeatDysfunctionException("Heart is in an invalid state!", e);
}
}
/**
* Executes the diastole phase of the heart.
*
* @throws Valve.IllegalValveStateException when one of the valves has an illegal State
*/
public void executeDiastole() throws Valve.IllegalValveStateException {
for (Half half : halves) {
half.closeSemilunarValve();
half.openAtrioventricularValve();
half.relaxAtrium();
half.relaxVentricle();
}
state = State.SYSTOLE;
}
/**
* Executes the systole phase of the heart.
*
* @throws Valve.IllegalValveStateException when one of the valves has an illegal State
*/
public void executeSystole() throws Valve.IllegalValveStateException {
for (Half half : halves) {
half.openSemilunarValve();
half.closeAtrioventricularValve();
half.contractAtrium();
half.contractVentricle();
}
state = State.DIASTOLE;
}
public State getState() {
return state;
}
public void setState(State state) {
this.state = state;
}
/**
* Sets the heart rate to the parameter value in Hz.
* Rate has to be inside range >30 && <220
* If rate is outside of range method rejects the change
* and returns false.
*
* @param frequencyInHz which should be applied to the heart
* @return true if the heart rate could be set, false otherwise
*/
public boolean setHeartRate(int frequencyInHz) {
if (frequencyInHz < 30 || frequencyInHz > 220) {
return false;
}
this.heartRate = frequencyInHz;
return true;
}
public int getHeartRate() {
return heartRate;
}
public List<Half> getHalves() {
return halves;
}
public static class HeartBeatDysfunctionException extends Exception {
public HeartBeatDysfunctionException() {
}
public HeartBeatDysfunctionException(String message) {
super(message);
}
public HeartBeatDysfunctionException(String message, Throwable cause) {
super(message, cause);
}
}
/**
* The main method instantiates a heart object and executes a single heartbeat.
*
* @param args
*/
public static void main(String[] args) throws HeartBeatDysfunctionException {
Heart heart = new Heart();
heart.executeHeartBeat();
}
}

View File

@ -0,0 +1,9 @@
package ch.zhaw.prog2.heartbeat;
public class InvalidValvePositionException extends RuntimeException {
public InvalidValvePositionException (String message) {
super (message);
}
}

View File

@ -0,0 +1,44 @@
package ch.zhaw.prog2.heartbeat;
/**
* This class represents a pacemaker for a human hart.
*
* This is an incomplete implementation, reduced to the essentials for the content of the lab.
* There would be a lot more code needed to implement a pacemaker, but this is not part of this lab :-)
*
* @author muon
*
*/
public class Pacemaker {
Heart heart;
/**
* Constructor of Pacemaker
* @param heart
*/
public Pacemaker(Heart heart) {
this.heart = heart;
}
/**
* Sets the heart rate to the parameter value in Hz.
* Rate has to be inside range >30 && <220
* If frequency can be applied on heart, the current frequency will be returned.
* If heart does reject the change the method throws an exception.
*
* @param frequencyInHz needs to be applied on heart
* @return current frequency of the heart
* @throws IllegalArgumentException when heart does reject the change
*/
public int setHeartRate(int frequencyInHz) {
if(!heart.setHeartRate(frequencyInHz)){
throw new IllegalArgumentException("Frequency could not be set.");
}
return heart.getHeartRate();
}
/*
...
There would be a lot more code needed to implement a pacemaker, but this is not part of this lab :-)
...
*/
}

View File

@ -0,0 +1,19 @@
package ch.zhaw.prog2.heartbeat.parts;
import ch.zhaw.prog2.heartbeat.Half.Side;
import ch.zhaw.prog2.heartbeat.Heart;
public class AtrioventricularValve extends Valve {
public AtrioventricularValve(Side side) {
super (side);
}
public void initializeState(Heart.State state) {
if(Heart.State.DIASTOLE.equals(state)){
setOpen(false);
}else{
setOpen(true);
}
}
}

View File

@ -0,0 +1,20 @@
package ch.zhaw.prog2.heartbeat.parts;
import ch.zhaw.prog2.heartbeat.Half.Side;
public class Atrium {
private Side side;
public Atrium (Side side) {
this.side = side;
}
public void contract() {
System.out.println("Atrium "+ side + " is contracting.");
}
public void relax() {
System.out.println("Atrium "+ side + " is relaxing.");
}
}

View File

@ -0,0 +1,20 @@
package ch.zhaw.prog2.heartbeat.parts;
import ch.zhaw.prog2.heartbeat.Half.Side;
import ch.zhaw.prog2.heartbeat.Heart;
public class SemilunarValve extends Valve {
public SemilunarValve(Side side) {
super (side);
}
public void initializeState(Heart.State state) {
if(Heart.State.DIASTOLE.equals(state)){
setOpen(true);
}else{
setOpen(false);
}
}
}

View File

@ -0,0 +1,61 @@
package ch.zhaw.prog2.heartbeat.parts;
import ch.zhaw.prog2.heartbeat.Half.Side;
public abstract class Valve {
private boolean open;
private Side side;
public Valve(Side side) {
this.side = side;
}
/**
* Opens the valve
*
* @throws IllegalValveStateException when the valve is already open
*/
public void open() throws IllegalValveStateException {
if (open) {
throw new IllegalValveStateException(this.getClass().getSimpleName() + " " + side + " valve is already open.");
}
System.out.println(this.getClass().getSimpleName() + " " + side + " is opening.");
open = true;
}
/**
* Closes the valve
*
* @throws IllegalValveStateException when valve is already closed
*/
public void close() throws IllegalValveStateException {
if (!open) {
throw new IllegalValveStateException(this.getClass().getSimpleName() + " " + side + " valve is already closed.");
}
System.out.println(this.getClass().getSimpleName() + " " + side + " is closing.");
open = false;
}
public boolean isOpen() {
return open;
}
protected void setOpen(Boolean open) {
this.open = open;
}
public static class IllegalValveStateException extends Exception {
public IllegalValveStateException() {
}
public IllegalValveStateException(String message) {
super(message);
}
public IllegalValveStateException(String message, Throwable cause) {
super(message, cause);
}
}
}

View File

@ -0,0 +1,20 @@
package ch.zhaw.prog2.heartbeat.parts;
import ch.zhaw.prog2.heartbeat.Half.Side;
public class Ventricle {
private Side side;
public Ventricle (Side side) {
this.side = side;
}
public void contract() {
System.out.println("Chamber "+ side + " is contracting.");
}
public void relax() {
System.out.println("Chamber "+ side + " is relaxing.");
}
}

View File

@ -0,0 +1,118 @@
/*
* Test Class for Heart
*/
package ch.zhaw.prog2.heartbeat;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
import ch.zhaw.prog2.heartbeat.parts.Valve;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import ch.zhaw.prog2.heartbeat.Heart.State;
class HeartTest {
/**
* This is a very simple test to check if Junit and Mockito are properly set up.
*/
@Test
void testTheTest() {
Heart classUnderTest = new Heart();
assertNotNull(classUnderTest.getState(), "The heart must have a state.");
}
/**
* Tests a single heartbeat
*/
@Test
void testHeartBeat() throws Heart.HeartBeatDysfunctionException {
Heart heart = new Heart();
State startState = heart.getState();
heart.executeHeartBeat();
// after one heartbeat, the heart must be in the same state as before
assertEquals(startState, heart.getState());
}
/**
* Tests if the valves are open or closed depending on the status of the heart
*/
@Test
void testValveStatus() throws Heart.HeartBeatDysfunctionException {
Heart heart = new Heart();
heart.executeHeartBeat();
State state = heart.getState();
if (state.equals(Heart.State.DIASTOLE)) {
for (Half half : heart.getHalves()) {
assertFalse(half.isAtrioventricularValveOpen());
assertTrue(half.isSemilunarValveOpen());
}
} else if ((state.equals(Heart.State.SYSTOLE))) {
for (Half half : heart.getHalves()) {
assertTrue(half.isAtrioventricularValveOpen());
assertFalse(half.isSemilunarValveOpen());
}
}
}
/**
* Tests if the hart throws the appropriate Exception, when malfunction was detected during hartBeat
*/
@Test
void testExecuteHeartBeatErrorBehaviour() {
Heart heart = new Heart();
// prepare error situation due to wrong initialization
heart.setState(State.SYSTOLE);
assertThrows(Heart.HeartBeatDysfunctionException .class, // verification using lambda
() -> heart.executeHeartBeat());
}
/**
* Tests if the hart throws the appropriate Exception, when malfunction was detected during hartBeat
* with exception Stubbing
*/
@Disabled
void testExecuteHartBeatErrorBehaviourWithStubbing() throws Valve.IllegalValveStateException {
//TODO implement and replace the annotation @Disabled by @Test
fail();
}
/**
* We test if Heart::executeHeartbeat() sends the right signals to both of its
* halves.
*
* When Half::contractVentricle() is called, Half::closeAtrioventricularValve()
* and Half::openSemilunarValve() must have been called earlier.
*
*/
@Disabled
void testValvesBehavior() {
//TODO implementand replace the annotation @Disabled by @Test
fail();
}
/**
* This is code used for the lecture slide.
*/
@Test
void testForSlide() throws Valve.IllegalValveStateException {
Half mockedHalf = mock(Half.class);
Heart heart = new Heart(mockedHalf, new Half(Half.Side.RIGHT));
heart.setState(State.SYSTOLE);
heart.initalizeState();
when(mockedHalf.isAtrioventricularValveOpen()).thenReturn(false);
when(mockedHalf.isSemilunarValveOpen()).thenReturn(true);
heart.executeSystole();
verify(mockedHalf).contractVentricle();
verify(mockedHalf, times(1)).contractAtrium();
}
}

View File

@ -0,0 +1,31 @@
package ch.zhaw.prog2.heartbeat;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
/*
* Test Class for Pacemaker
*/
public class PacemakerTest {
/**
* Test if setHeartRate does throw correct exception when rate is rejected (because frequency is out of range)
*/
@Disabled
void testSetHeartRateRejectsFrequenciesOutOfRange() {
//TODO implement and replace the annotation @Disabled by @Test
fail();
}
/**
* Test if setHeartRate does correctly set the rate when frequency is inside range
*/
@Disabled
void testSetHeartRateAppliesFrequenciesInsideRange() {
//TODO implement and replace the annotation @Disabled by @Test
fail();
}
}

View File

@ -0,0 +1,99 @@
:source-highlighter: coderay
:icons: font
:experimental:
:!sectnums:
:imagesdir: ../images/
:handout: ./code/
:logo: IT.PROG2 -
ifdef::backend-html5[]
:logo: image:PROG2-300x300.png[IT.PROG2,100,100,role=right,fit=none,position=top right]
endif::[]
ifdef::backend-pdf[]
:logo:
endif::[]
ifdef::env-github[]
:tip-caption: :bulb:
:note-caption: :information_source:
:important-caption: :heavy_exclamation_mark:
:caution-caption: :fire:
:warning-caption: :warning:
endif::[]
= {logo} Lösungen zum Praktikum Mock-Testing
:sectnums:
:sectnumlevels: 2
// Beginn des Aufgabenblocks
== Herz
****
Funktionserläuterung zum Herzschlag finden Sie in der Aufgabenstellung
****
== Aufgaben
=== Einführung in Mockito
[loweralpha]
. Studieren Sie die Testmethoden `HeartTest::testValveStatus()` und `HeartTest::testExecuteHartBeatErrorBehaviour()`.
Dort wird *ein Teil* des Verhaltens des Herzens getestet.
. Implementieren Sie die Methoden `Heart::executeDiastole()`, `Heart::executeSystole()` und `Heart::executeHeartBeat()` sodass die bestehenden Tests durchlaufen und das oben beschriebene Verhalten des Herzens modelliert wird.
. (optional) Ein echtes Herz hat eine Schlagfrequenz.
Implementieren Sie, dass das Herz nach jeder Systole pausiert.
****
Siehe Musterlösung: `Heart.executeDiastole()`, `Heart.executeSystole()` und `Heart.executeHeartBeat()`
****
=== Fragen zu Testing [TU]
[loweralpha]
. Testing kann in zwei unterschiedliche Strategien aufgeteilt werden.
Zum einen gibt es White-Box-Testing und zum zweiten Black-Box-Testing.
Was für Java Libraries gibt es, um diese zwei Strategien zu testen?
Wann wenden Sie welche Strategie an?
+
****
* JUnit ist ein Framework für Unit-Tests (auch Modul-Tests genannt).
Es wird sowohl für White-Box-Testing als auch für Black-Box-Testing angewendet.
* Für White-Box-Testing eignet sich Mockito, weil damit die Abläufe innerhalb einer Klasse getestet werden können (behavior testing).
* Black-Box-Testing trifft keine Annahmen darüber, *wie* eine Klasse oder Methode eine Aufgabe erledigt.
Es wird lediglich überprüft, ob auf eine bestimmte Eingabe die erwartete Ausgabe erfolgt.
* Nichttriviale Methoden sollten immer mindestens mit Black-Box-Testing getestet werden.
Diese Tests werden am besten von einer anderen Person geschrieben als von der Programmierer:in.
* Für White-Box-Testing werden Informationen benötigt, *wie* eine Klasse oder Methode eine Aufgabe erledigt.
****
. Das Erstellen von guten automatisierten Unit-Tests kann manchmal schwierig umzusetzen sein.
Was ist der Hauptgrund dafür? Wie können Sie dieses Problem entschärfen?
+
****
* Das Setup eines Unit-Tests kann kompliziert werden, wenn mehrere Klassen dafür instanziiert und konfiguriert werden müssen.
* Das Problem kann entschärft werden, indem
** die verschiedenen Klassen besser entkoppelt werden und
** die Klassen, von denen die zu testende Klasse abhängig ist, zu mocken.
****
. Der Testfokus war bisher auf der Klasse `Heart`.
Testen Sie jetzt die Klasse `Half`. Wo verwenden Sie Stubbing, wo Mocking?
+
****
* Die Funktionalität der Klasse Half nicht besonders umfangreich.
Alle Methoden der Klasse bestehen aus nur genau einer Zeile und die Klasse hat bis auf das Datenfeld `Half.side` keinen State.
Was schieflaufen könnte ist, dass jemand beispielweise auf einem Ventil anstatt der `close()` Methode die `open()` Methode aufruft.
Weil wir in der Klasse `Half` nicht wirklich einen Status prüfen können, macht es mehr Sinn das Verhalten der Klasse zu prüfen (ruft die Klasse die richtigen Methoden auf)
→ Das können wir mit Mocking (in Mockito mit `verify`) erreichen.
Entsprechend würde sich hier ein Mock besser eignen als ein Stub.
Über die Frage, wie sinnvoll es ist solch einfache Klassen zu simulieren, lässt sich Diskutieren und ist abhängig vom jeweiligen Testkonzept.
* Beim Auftrag die Klasse `Half` zu testen, stossen Sie auf das Problem, dass Sie weder Stubs noch Mocks anwenden können, weil die Klassen von welchen `Half` abhängt direkt im Konstruktor von `Half` initialisiert werden.
Damit können Sie kein Test-Double verwenden (injecten).
Das Problem könnten Sie lösen, wenn es einen entsprechenden Konstruktor in der Klasse `Half` gäbe, welche die Instanzen der Abhängigen Typen entgegennimmt (analog zu `Heart`).
****

File diff suppressed because one or more lines are too long