Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Yea :) #24

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions src/main/java/fakes/FakeUserValidator.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package fakes;

public class FakeUserValidator extends UserValidator {
private boolean userExists;

@Override
public boolean doesUsernameExist(String username) {
return this.userExists;
}

public boolean doesUsernameExist(User usr, Database db) {
for(User user : db.getUsers()){
if (user.getUsername().equals(usr.getUsername())){
return true;
}
}
return false;
}

public void setUserExists(boolean userExists) {
this.userExists = userExists;
}
}
51 changes: 51 additions & 0 deletions src/main/java/fakes/InjectDemo.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
package fakes;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;

interface CanLog {
void log(String message);
}

class FileLogger implements CanLog {
@Override
public void log(String message) {
try {
Files.write(Paths.get("src/main/resources/log.txt"), message.getBytes(StandardCharsets.UTF_8));
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}

class ConsoleLogger implements CanLog {
@Override
public void log(String message) {
System.out.println("LOG: " + message);
}
}

class Logger {
private final CanLog canLog;

public Logger(CanLog canLog) {
this.canLog = canLog;
}

public void doLog(String message) {
canLog.log(message);
}
}

public class InjectDemo {

public static void main(String[] args) {
final Logger logger = new Logger(new FileLogger());
logger.doLog("test log 1");

final Logger logger2 = new Logger(new ConsoleLogger());
logger2.doLog("test log 2");
}
}
19 changes: 14 additions & 5 deletions src/main/java/fakes/UserController.java
Original file line number Diff line number Diff line change
@@ -1,20 +1,29 @@

package fakes;

public class UserController {

private static Database db = FileDatabase.getInstance();
private final Database db;
private final UserValidator uv;

public UserController(UserValidator uv, Database db) {
this.uv = uv;
this.db = db;
}

public Message create(User user){
if(user == null){
throw new IllegalArgumentException("user required");
}
Boolean canCreate = UserValidator.isValidUsername(user.getUsername())
&& !UserValidator.doesUsernameExist(user.getUsername());
Boolean canCreate = this.uv.isValidUsername(user.getUsername())
&& !this.uv.doesUsernameExist(user.getUsername());
if(canCreate){
db.addUser(user);
this.db.addUser(user);
return Message.createOK();
}else{
return Message.createNotOK();
}
}
}


}
52 changes: 41 additions & 11 deletions src/main/java/fakes/UserValidator.java
Original file line number Diff line number Diff line change
@@ -1,25 +1,55 @@
package fakes;

public class UserValidator {
import java.util.Locale;

private static Database db = FileDatabase.getInstance();
public class UserValidator {
private static Database db;

public static boolean doesUsernameExist(String username){
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
public UserValidator() {
this.db = FileDatabase.getInstance();
}
public UserValidator(Database db) {
this.db = db;
}
public boolean doesUsernameExist(String username){
// try {
// Thread.sleep(5000);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }

for(User user : db.getUsers()){
if (user.getUsername().equals(username)){
if (user.getUsername().toLowerCase(Locale.ROOT).equals(username.toLowerCase(Locale.ROOT))){
return true;
}
}
return false;
}

public static boolean isValidUsername(String username){
return true;
boolean result = true;

// usernameContainsNumberButNotAsFirstChar
// starte mit i=1 damit der index 0 nicht beruecksichtigt wird
for(int i = 1; i < username.length(); i++) {
char testChar = username.charAt(i);
if(Character.isDigit(testChar)) {
return true;
}
}

char[] chars = username.toCharArray();
for(char c : chars) {
// usernameOnlyLetters
if(!Character.isLetter(c)) {
result = false;
}
// usernameContainsAnyNonAlphaNumericChar
if(!Character.isLetterOrDigit(c)) {
result = false;
}
}
return result;
}
}

}
17 changes: 17 additions & 0 deletions src/main/java/fakes/mockDatabase.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package fakes;

import java.util.ArrayList;
import java.util.List;

public class mockDatabase extends Database {
List<User> users = new ArrayList<>();
@Override
public void addUser(User user) {
users.add(user);
}

@Override
public List<User> getUsers() {
return users;
}
}
111 changes: 93 additions & 18 deletions src/test/java/fakes/UserControllerTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,13 @@
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;

import javax.xml.crypto.Data;

import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.*;
import static org.mockito.Mockito.times;

class UserControllerTest {

// Pro getestete Methode gibt es eine inner class (Hier für UserController.create)
Expand All @@ -13,44 +20,112 @@ class create {
// --- Testing with Fakes ---

@Test
void withValidInexistingUsername_returnsOK__NO_FAKE() {
UserController ctrl = new UserController();
@org.junit.jupiter.api.Disabled
void withValidInexistingUsername_returnsOK__NO_FAKE_DEMO() {
// Arrange
UserController ctrl = new UserController(new UserValidator(), FileDatabase.getInstance());
User user = new User("kalua");

// Act
Message result = ctrl.create(user);

// Assert
Assertions.assertEquals(result.status, Message.Status.OK);
}

@Test
void withValidInexistingUsername_returnsOK__FAKE() {
// TODO
void withValidInexistentUsername_returnsOK__FAKE() {
// 1. Test schneller machen
// 2. UserController.create so beinflussen,
// 2. UserController.create so beeinflussen,
// dass einmal der "if"- und einmal der "else"-Fall durchlaufen wird

// Tipp: Welche Methode sorgt dafür, dass canCreate im UserController true bzw. false ist?
// Kannst du deren Rückgabetyp beeinflussen?

// Die Schritte die du ausprogrammieren musst:
// 1. Arrange: UserController mit allen Abhängigkeiten initialisieren
// 2. Act: UserController.create Methode aufrufen
// 3. Assert: Rückgabewert von UserController.create prüfen

// -> implement test
/* Arrange */
FakeUserValidator uv = new FakeUserValidator();
UserController uc = new UserController(uv, new mockDatabase());
User user = new User("kalua");
/* Act */
Message result = uc.create(user);
/* Assert */
Assertions.assertEquals(result.status, Message.Status.OK);
}

@Test
void withValidInexistingUsername_returnsOK__MOCKITO() {
// TODO
void withValidInexistentUsername_returnsOK__MOCKITO() {
// -> implement test
/* ARRANGE */
UserValidator uv = mock(UserValidator.class);
FileDatabase db = mock(FileDatabase.class);
UserController uc = new UserController(uv, db);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Du solltest hier noch definieren was isValidUsername und doesUsernameExists retournieren sollen. Denn by default retournieren gemockte boolean Methoden ja false.

User user = new User("kalua");
/* ACT */
Message result = uc.create(user);
/* ASSERT */
Assertions.assertEquals(result.status, Message.Status.OK);
}

@Test
void withValidInexitingUserName_addUserToDB__FAKE() {
// TODO
void withValidInexistentUsername_shouldAddUserToDB__FAKE() {
// Der Test soll prüfen, ob der Benutzer tatsächlich der DB hinzugefügt wurde.
// Dazu soll ein Mock-Objekt für die Database Klasse verwendet werden.

// -> implement test
// Tipp: Wie kann dein Test feststellen, ob der UserController der Datenbank einen Benutzer hinzugefügt hat?
// Welche Art von Fake (Stub oder Mock) kann dir weiterhelfen?
/* ARRANGE */
FakeUserValidator uv = new FakeUserValidator();
uv.setUserExists(false);
mockDatabase db = new mockDatabase();
UserController uc = new UserController(uv, db);
User user = new User("kalua");
/* ACT */
Message result = uc.create(user);
boolean result2 = uv.doesUsernameExist(user, db);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In allen Tests dieser Klasse ist das SUT der UserController.
Es ist also nicht nötig hier auf dem FakeUserValidator eine Methode aufzurufen. Du könntest aber prüfen ob db.getUsers() den gewünschten User retourniert.

/* ASSERT */
Assertions.assertEquals(result.status, Message.Status.OK);
Assertions.assertTrue(result2);
}

@Test
void withValidInexitingUserName_addUserToDB__MOCKITO() {
// TODO
void withValidInexistentUsername_shouldAddUserToDB__MOCKITO() {
// Der Test soll prüfen, ob der Benutzer tatsächlich der DB hinzugefügt wurde.
// Dazu soll ein Mock-Objekt für die Database Klasse verwendet werden.

// Tipp: Du kannst prüfen, ob der User hinzugefügt wurde,
// indem du prüfst wie of die Methode Database.addUser aufgerufen wurde.
// -> implement test
/* ARRANGE */
UserValidator uv = mock(UserValidator.class);
FileDatabase db = mock(FileDatabase.class);
UserController uc = new UserController(uv, db);
User user = new User("kalua");

doReturn(true).when(uv).isValidUsername(anyString());
// eigentlich müsste untenstehende anweisung rein, ergibt jedoch einen error... keine ahnung wieso.
//doReturn(true).when(uv).doesUsernameExist(anyString());
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Es wäre dann aber gemäss Testname "doReturn(false)" :). Was ist die Fehlermeldung?


/* ACT */
Message result = uc.create(user);
verify(db, times(1)).addUser(any());

/* ASSERT */
Assertions.assertEquals(result.status, Message.Status.OK);
}

// --- Testing Exceptions ---

@Test
void TRY_CATCH_withNullUser_throwsIllegalArgumentExc() {
void withNullUser_throwsIllegalArgumentExc__TRY_CATCH() {
try {
UserController ctrl = new UserController();
UserController ctrl = new UserController(new UserValidator(), FileDatabase.getInstance());
ctrl.create(null);
Assertions.fail("No IllegalArgumentException was thrown");
} catch (IllegalArgumentException ex) {
Expand All @@ -60,20 +135,20 @@ void TRY_CATCH_withNullUser_throwsIllegalArgumentExc() {
}

@Test
void THROWN_withNullUser_throwsIllegalArgumentException() {
void withNullUser_throwsIllegalArgumentException__THROWN() {
Assertions.assertThrows(IllegalArgumentException.class, () -> {
UserController ctrl = new UserController();
UserController ctrl = new UserController(new UserValidator(), FileDatabase.getInstance());
ctrl.create(null);
});
}

@Test
void THROWN_MESSAGE_withNullUser_throwsIllegalArgumentExceptionWithMessage() {
void withNullUser_throwsIllegalArgumentExceptionWithMessage__THROWN_MESSAGE() {
Exception thrown = Assertions.assertThrows(IllegalArgumentException.class, () -> {
UserController ctrl = new UserController();
UserController ctrl = new UserController(new UserValidator(), FileDatabase.getInstance());
ctrl.create(null);
});
Assertions.assertTrue(thrown.getMessage().contains("required"));
}
}
}
}
Loading