JUnit 5, Maven, Gradle ו-GitJUnit 5, Maven, Gradle & Git
בדיקות אוטומטיות עם JUnit 5, פרויקט Maven או Gradle, ניהול תלויות, ו-Git ו-GitHub.
Automated tests with JUnit 5, a Maven or Gradle project, dependencies, and Git and GitHub.
בדיקות לחילוקTests for division
תזכורת: מה ביקשוReminder: the task
כתבו assertEquals ו-assertThrows קטנות (כמו ב-JUnit), ובדקו את Calc.divide: 8/2 = 4, 7/2 = 3, ו-1/0 זורק ArithmeticException. הפלט: שלוש שורות PASS ... ואז 3/3 passed.
Write small assertEquals and assertThrows (like JUnit's), and test Calc.divide: 8/2 = 4, 7/2 = 3, and 1/0 throws ArithmeticException. The output: three PASS ... lines then 3/3 passed.
סימולציה: הפתרון רץ שורה אחרי שורהSimulation: the solution runs line by line
לוחצים הבא או נגן: רואים איזו שורה Java מבצעת, מה יש בכל קופסה (משתנה) ומה מופיע על המסך. זו הרצה אמיתית של הפתרון.
Press Next or Play: see which line Java runs, what is in each box (variable) and what appears on the screen. This is a real run of the solution.
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
הפתרון המלא והפלט שלוFull solution and its output
public class Main {
static int passed = 0;
static int total = 0;
static void assertEquals(Object expected, Object actual, String name) {
total++;
if (expected.equals(actual)) {
passed++;
System.out.println("PASS " + name);
} else {
System.out.println("FAIL " + name + ": expected " + expected + " but was " + actual);
}
}
static void assertThrows(Class<? extends Exception> type, Action code, String name) {
total++;
try {
code.run();
System.out.println("FAIL " + name + ": nothing was thrown");
} catch (Exception e) {
if (type.isInstance(e)) {
passed++;
System.out.println("PASS " + name);
} else {
System.out.println("FAIL " + name + ": got " + e.getClass().getSimpleName());
}
}
}
public static void main(String[] args) {
assertEquals(4, Calc.divide(8, 2), "divides evenly");
assertEquals(3, Calc.divide(7, 2), "drops the remainder");
assertThrows(ArithmeticException.class, () -> Calc.divide(1, 0), "refuses zero");
System.out.println(passed + "/" + total + " passed");
}
}
class Calc {
static int divide(int a, int b) {
return a / b;
}
}
interface Action {
void run();
}PASS divides evenly PASS drops the remainder PASS refuses zero 3/3 passed
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
צייד באגים: הבדיקות מצאו באגBug hunter: the tests found a bug
תזכורת: מה ביקשוReminder: the task
הבדיקות של isLeap מדפיסות FAIL 1900 is not (divisible by 100). אל תשנו את הבדיקות: תקנו את isLeap (שנה מעוברת: מתחלקת ב-4 ולא ב-100, או מתחלקת ב-400) עד 4/4 passed.
The isLeap tests print FAIL 1900 is not (divisible by 100). Don't change the tests: fix isLeap (a leap year divides by 4 and not by 100, or divides by 400) until 4/4 passed.
סימולציה: הפתרון רץ שורה אחרי שורהSimulation: the solution runs line by line
לוחצים הבא או נגן: רואים איזו שורה Java מבצעת, מה יש בכל קופסה (משתנה) ומה מופיע על המסך. זו הרצה אמיתית של הפתרון.
Press Next or Play: see which line Java runs, what is in each box (variable) and what appears on the screen. This is a real run of the solution.
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
הפתרון המלא והפלט שלוFull solution and its output
public class Main {
static int passed = 0;
static int total = 0;
static void assertEquals(Object expected, Object actual, String name) {
total++;
if (expected.equals(actual)) {
passed++;
System.out.println("PASS " + name);
} else {
System.out.println("FAIL " + name + ": expected " + expected + " but was " + actual);
}
}
public static void main(String[] args) {
assertEquals(true, Dates.isLeap(2024), "2024 is leap");
assertEquals(false, Dates.isLeap(2023), "2023 is not");
assertEquals(false, Dates.isLeap(1900), "1900 is not (divisible by 100)");
assertEquals(true, Dates.isLeap(2000), "2000 is leap (divisible by 400)");
System.out.println(passed + "/" + total + " passed");
}
}
class Dates {
static boolean isLeap(int year) {
return (year % 4 == 0 && year % 100 != 0) || year % 400 == 0;
}
}PASS 2024 is leap PASS 2023 is not PASS 1900 is not (divisible by 100) PASS 2000 is leap (divisible by 400) 4/4 passed
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
קודם בדיקה, אחר כך קודTest first, code later
תזכורת: מה ביקשוReminder: the task
הבדיקות של Text.slug כבר כתובות ונכשלות. כתבו את slug כך ששלושתן יעברו: אותיות קטנות, בלי רווחים בקצוות, וכל רצף רווחים הופך למקף אחד.
The tests for Text.slug are already written and failing. Write slug so all three pass: lower case, no spaces at the ends, and every run of spaces becomes one dash.
סימולציה: הפתרון רץ שורה אחרי שורהSimulation: the solution runs line by line
לוחצים הבא או נגן: רואים איזו שורה Java מבצעת, מה יש בכל קופסה (משתנה) ומה מופיע על המסך. זו הרצה אמיתית של הפתרון.
Press Next or Play: see which line Java runs, what is in each box (variable) and what appears on the screen. This is a real run of the solution.
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
הפתרון המלא והפלט שלוFull solution and its output
public class Main {
static int passed = 0;
static int total = 0;
static void assertEquals(Object expected, Object actual, String name) {
total++;
if (expected.equals(actual)) {
passed++;
System.out.println("PASS " + name);
} else {
System.out.println("FAIL " + name + ": expected " + expected + " but was " + actual);
}
}
public static void main(String[] args) {
assertEquals("hello-world", Text.slug("Hello World"), "lower case and dash");
assertEquals("dune", Text.slug(" Dune "), "trims");
assertEquals("a-b-c", Text.slug("a b c"), "many spaces become one dash");
System.out.println(passed + "/" + total + " passed");
}
}
class Text {
static String slug(String s) {
return s.trim().toLowerCase().replaceAll("\\s+", "-");
}
}PASS lower case and dash PASS trims PASS many spaces become one dash 3/3 passed
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
מצב נקי לכל בדיקהA clean state per test
תזכורת: מה ביקשוReminder: the task
newShelf() עושה מה ש-@BeforeEach עושה: מדף חדש עם Dune. כתבו ארבע בדיקות (הוספה, גודל, דחיית כפול, גודל שנשאר) כך שכל זוג מקבל מדף משלו. הפלט: ארבע PASS ו-4/4 passed.
newShelf() does what @BeforeEach does: a new shelf with Dune. Write four tests (adding, size, rejecting a duplicate, size unchanged) so each pair gets its own shelf. The output: four PASS and 4/4 passed.
סימולציה: הפתרון רץ שורה אחרי שורהSimulation: the solution runs line by line
לוחצים הבא או נגן: רואים איזו שורה Java מבצעת, מה יש בכל קופסה (משתנה) ומה מופיע על המסך. זו הרצה אמיתית של הפתרון.
Press Next or Play: see which line Java runs, what is in each box (variable) and what appears on the screen. This is a real run of the solution.
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
הפתרון המלא והפלט שלוFull solution and its output
import java.util.ArrayList;
import java.util.List;
public class Main {
static int passed = 0;
static int total = 0;
static void assertEquals(Object expected, Object actual, String name) {
total++;
if (expected.equals(actual)) {
passed++;
System.out.println("PASS " + name);
} else {
System.out.println("FAIL " + name + ": expected " + expected + " but was " + actual);
}
}
static Shelf newShelf() {
Shelf s = new Shelf();
s.add("Dune");
return s;
}
public static void main(String[] args) {
Shelf a = newShelf();
assertEquals(true, a.add("Emma"), "adds a new title");
assertEquals(2, a.size(), "size grows");
Shelf b = newShelf();
assertEquals(false, b.add("Dune"), "rejects a duplicate");
assertEquals(1, b.size(), "size stays");
System.out.println(passed + "/" + total + " passed");
}
}
class Shelf {
private final List<String> titles = new ArrayList<>();
boolean add(String t) {
if (titles.contains(t)) {
return false;
}
return titles.add(t);
}
int size() {
return titles.size();
}
}PASS adds a new title PASS size grows PASS rejects a duplicate PASS size stays 4/4 passed
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
Git ראשוןFirst Git
תזכורת: מה ביקשוReminder: the task
במחשב שלכם, בתיקיית java-course: אתחלו מאגר Git, הוסיפו את כל הקבצים, צרו commit ראשון, והסתכלו בהיסטוריה ובמצב.
On your computer, in the java-course folder: initialise a Git repository, add all the files, make a first commit, and look at the history and the status.
הפתרון המלא והפלט שלוFull solution and its output
cd java-course
git init
git add .
git commit -m "First shelf version"
git log --oneline
git statusיש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
מדף, צעד 30: בדיקות למדףShelf, step 30: tests for the shelf
תזכורת: מה ביקשוReminder: the task
כתבו שלוש בדיקות למדף בתור מתודות עם שמות של JUnit (addsANewBook, rejectsADuplicate, throwsWhenMissing), כל אחת עם מדף חדש, וסיכום בסגנון Maven: Tests run: 3, Failures: 0. אחר כך העבירו אותן לקובץ JUnit אמיתי כמו בתזכורת (אתגר 1).
Write three shelf tests as methods with JUnit names (addsANewBook, rejectsADuplicate, throwsWhenMissing), each with a fresh shelf, and a Maven-style summary: Tests run: 3, Failures: 0. Then move them into a real JUnit file like the refresher (challenge 1).
סימולציה: הפתרון רץ שורה אחרי שורהSimulation: the solution runs line by line
לוחצים הבא או נגן: רואים איזו שורה Java מבצעת, מה יש בכל קופסה (משתנה) ומה מופיע על המסך. זו הרצה אמיתית של הפתרון.
Press Next or Play: see which line Java runs, what is in each box (variable) and what appears on the screen. This is a real run of the solution.
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
הפתרון המלא והפלט שלוFull solution and its output
import java.util.ArrayList;
import java.util.List;
public class Main {
static int passed = 0;
static int total = 0;
static void assertEquals(Object expected, Object actual, String name) {
total++;
if (expected.equals(actual)) {
passed++;
System.out.println("PASS " + name);
} else {
System.out.println("FAIL " + name + ": expected " + expected + " but was " + actual);
}
}
static void addsANewBook() {
Shelf s = new Shelf();
assertEquals(true, s.add(new Book("Emma", "Austen")), "addsANewBook");
}
static void rejectsADuplicate() {
Shelf s = new Shelf();
s.add(new Book("Dune", "Herbert"));
assertEquals(false, s.add(new Book("Dune", "Herbert")), "rejectsADuplicate");
}
static void throwsWhenMissing() {
Shelf s = new Shelf();
String result;
try {
s.find("Hamlet");
result = "nothing thrown";
} catch (BookNotFoundException e) {
result = "thrown";
}
assertEquals("thrown", result, "throwsWhenMissing");
}
public static void main(String[] args) {
addsANewBook();
rejectsADuplicate();
throwsWhenMissing();
System.out.println("Tests run: " + total + ", Failures: " + (total - passed));
}
}
record Book(String title, String author) {
}
class BookNotFoundException extends Exception {
BookNotFoundException(String title) {
super("No book titled '" + title + "'");
}
}
class Shelf {
private final List<Book> books = new ArrayList<>();
boolean add(Book b) {
if (books.contains(b)) {
return false;
}
return books.add(b);
}
Book find(String title) throws BookNotFoundException {
for (Book b : books) {
if (b.title().equals(title)) {
return b;
}
}
throw new BookNotFoundException(title);
}
}PASS addsANewBook PASS rejectsADuplicate PASS throwsWhenMissing Tests run: 3, Failures: 0
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
פרויקט Maven עם JUnitA Maven project with JUnit
תזכורת: מה ביקשוReminder: the task
במחשב שלכם: צרו פרויקט Maven, הוסיפו ל-pom.xml את התלות org.junit.jupiter:junit-jupiter (בגרסה עדכנית, scope test), העתיקו את Shelf ואת ShelfTest מהתזכורת, הריצו mvn test, ואחר כך mvn package.
On your computer: create a Maven project, add the org.junit.jupiter:junit-jupiter dependency to pom.xml (a current version, scope test), copy Shelf and ShelfTest from the refresher, run mvn test, then mvn package.
הפתרון המלא והפלט שלוFull solution and its output
mvn archetype:generate -DgroupId=dev.shelf -DartifactId=shelf -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false
cd shelf
# מעתיקים את Shelf.java ל-src/main/java ואת ShelfTest.java ל-src/test/java
mvn test
mvn package
java -cp target/shelf-1.0-SNAPSHOT.jar dev.shelf.Appmvn archetype:generate -DgroupId=dev.shelf -DartifactId=shelf -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false
cd shelf
# copy Shelf.java to src/main/java and ShelfTest.java to src/test/java
mvn test
mvn package
java -cp target/shelf-1.0-SNAPSHOT.jar dev.shelf.Appיש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
ענף, מיזוג ו-GitHubA branch, a merge and GitHub
תזכורת: מה ביקשוReminder: the task
פתחו ענף feature/ratings, שנו משהו ושמרו commit, חזרו ל-main ומזגו. צרו מאגר ריק ב-GitHub והעלו אליו.
Open a feature/ratings branch, change something and commit, go back to main and merge. Create an empty repository on GitHub and push to it.
הפתרון המלא והפלט שלוFull solution and its output
git switch -c feature/ratings
# משנים קוד ושומרים
git add .
git commit -m "Add ratings"
git switch main
git merge feature/ratings
git remote add origin https://github.com/<you>/shelf.git
git push -u origin maingit switch -c feature/ratings
# change some code and save
git add .
git commit -m "Add ratings"
git switch main
git merge feature/ratings
git remote add origin https://github.com/<you>/shelf.git
git push -u origin mainיש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.