Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
Prev Previous commit
Next Next commit
Added tests for protection agains mutation of the list object
  • Loading branch information
FridaTveit committed Jan 21, 2017
commit feecb1c852802ae68681b73b8d3069079e95f4ab
7 changes: 5 additions & 2 deletions exercises/grade-school/src/example/java/School.java
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,15 @@ public int numberOfStudents() {
}

public void add(String student, int grade) {
List<String> students = grade(grade);
List<String> students = fetchGradeFromDatabase(grade);
students.add(student);
}

public List<String> grade(int grade) {
// Leaks internal storage to caller
return new ArrayList<>(fetchGradeFromDatabase(grade));
}

private List<String> fetchGradeFromDatabase(int grade) {
if (!database.containsKey(grade)) {
database.put(grade, new LinkedList<>());
}
Expand Down
29 changes: 29 additions & 0 deletions exercises/grade-school/src/test/java/SchoolTest.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
import org.junit.Ignore;
import org.junit.Test;

import java.lang.Integer;
import java.util.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
Expand Down Expand Up @@ -83,4 +86,30 @@ public void sortsSchool() {
sortedStudents.put(3, Arrays.asList("Kyle"));
assertEquals(school.studentsByGradeAlphabetical(), sortedStudents);
}

@Ignore
@Test
public void modifyingFetchedGradeShouldNotModifyInternalDatabase() {
String shouldNotBeAdded = "Should not be added to school";
int grade = 1;

List<String> students = school.grade(grade);
students.add(shouldNotBeAdded);

assertThat(school.grade(grade), not(hasItem(shouldNotBeAdded)));
}

@Ignore
@Test
public void modifyingSortedStudentsShouldNotModifyInternalDatabase() {
int grade = 2;
String studentWhichShouldNotBeAdded = "Should not be added";
List<String> listWhichShouldNotBeAdded = new ArrayList<>();
listWhichShouldNotBeAdded.add(studentWhichShouldNotBeAdded);

Map<Integer, List<String>> sortedStudents = school.studentsByGradeAlphabetical();
sortedStudents.put(grade,listWhichShouldNotBeAdded);

assertThat(school.studentsByGradeAlphabetical().get(grade), not(hasItem(studentWhichShouldNotBeAdded)));
}
}