נבנה על ידיBuilt by Ariel Yohimovich

JavaJava
30
חלקPart 5: Java מודרנית וכליםModern Java & tools כ-3 שעות (כולל הפסקה)About 3 hours (with a break)

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.

01המונחים של המפגשThis session's terms

לפני הקוד, המילים. כל מונח כאן מקושר גם במילון של הקורס.

Before the code, the words. Every term here is also linked in the course glossary.

  • בדיקת יחידה: קוד קטן שבודק יחידה אחת (מתודה, מחלקה) במצב אחד: מכינים (Arrange), מפעילים (Act), ובודקים את התוצאה (Assert). רץ בשנייה, ואפשר להריץ אחרי כל שינוי.unit test: Small code checking one unit (a method, a class) in one situation: set up (Arrange), run (Act), check the result (Assert). It runs in a second, after every change.
  • JUnit 5: ספריית הבדיקות הנפוצה ב-Java. כל מתודה עם @Test היא בדיקה, @BeforeEach רץ לפני כל אחת, ו-IntelliJ או mvn test מריצים הכול ומדווחים.JUnit 5: Java's common testing library. Each @Test method is a test, @BeforeEach runs before each one, and IntelliJ or mvn test runs them all and reports.
  • assert: assertEquals(expected, actual), assertTrue, assertThrows(Type.class, () -> ...): אם הבדיקה נכשלת, JUnit מסמן FAIL ומראה מה היה צפוי ומה התקבל.assertion: assertEquals(expected, actual), assertTrue, assertThrows(Type.class, () -> ...): when one fails, JUnit marks FAIL and shows what was expected and what came.
  • Maven: כלי בנייה: קובץ pom.xml מגדיר את הפרויקט ואת התלויות (למשל JUnit), והוא מוריד אותן לבד. קוד ב-src/main/java, בדיקות ב-src/test/java. mvn test, mvn package.Maven: A build tool: pom.xml defines the project and its dependencies (e.g. JUnit), which it downloads itself. Code in src/main/java, tests in src/test/java. mvn test, mvn package.
  • Gradle: כלי בנייה נוסף, עם build.gradle במקום pom.xml. אותו מבנה תיקיות. gradle test, gradle build.Gradle: Another build tool, with build.gradle instead of pom.xml. The same folder layout. gradle test, gradle build.
  • Git: מערכת שמירת גרסאות: כל commit הוא תמונת מצב של הפרויקט עם הודעה. אפשר לחזור אחורה, לפתוח ענפים (branches) ולמזג. GitHub שומר עותק ברשת.Git: A version-control system: each commit is a snapshot of the project with a message. You can go back, open branches and merge. GitHub keeps a copy online.
  • commit: git add בוחר מה ייכנס, ו-git commit -m "..." שומר תמונת מצב. הודעה טובה אומרת מה השתנה ולמה.commit: git add picks what goes in, and git commit -m "..." saves a snapshot. A good message says what changed and why.

02בדיקה היא קוד שבודק קודA test is code that checks code

לפני JUnit, הרעיון עצמו ב-Java רגילה: כל בדיקה מפעילה את הקוד ומשווה לתוצאה צפויה. בדיקה טובה בודקת גם מקרי קצה (שלילי, אפס).

Before JUnit, the idea itself in plain Java: each test runs the code and compares with an expected result. A good test checks edge cases too (negative, zero).

Main.java
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) {
        Calculator c = new Calculator();
        assertEquals(5, c.add(2, 3), "adds two numbers");
        assertEquals(-1, c.add(2, -3), "adds a negative");
        assertEquals(0, c.add(0, 0), "zero plus zero");
        System.out.println(passed + "/" + total + " passed");
    }
}

class Calculator {
    int add(int a, int b) {
        return a + b;
    }
}
פלטOutput
PASS adds two numbers
PASS adds a negative
PASS zero plus zero
3/3 passed
צפו בהרצה צעד אחר צעדWatch it run, step by step
צפו בהרצהWatch it runשורה אחרי שורה, כמו ש-Java מבצעתLine by line, the way Java runs it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

03אותו דבר ב-JUnit 5The same in JUnit 5

ב-JUnit כל בדיקה היא מתודה עם @Test, ו-@BeforeEach בונה מדף חדש לפני כל אחת, כך שהבדיקות לא תלויות זו בזו. assertThrows בודק שנזרקה חריגה. ב-IntelliJ לוחצים על החץ הירוק שליד המחלקה.

In JUnit each test is a method with @Test, and @BeforeEach builds a fresh shelf before each one, so the tests don't depend on each other. assertThrows checks an exception was thrown. In IntelliJ, click the green arrow next to the class.

ShelfTest.java
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;

class ShelfTest {
    private Shelf shelf;

    @BeforeEach
    void setUp() {
        shelf = new Shelf();
        shelf.add(new Book("Dune", "Herbert"));
    }

    @Test
    void addsANewBook() {
        assertTrue(shelf.add(new Book("Emma", "Austen")));
        assertEquals(2, shelf.size());
    }

    @Test
    void rejectsADuplicate() {
        assertTrue(!shelf.add(new Book("Dune", "Herbert")));
        assertEquals(1, shelf.size());
    }

    @Test
    void throwsWhenTheBookIsMissing() {
        assertThrows(BookNotFoundException.class, () -> shelf.find("Hamlet"));
    }
}
להרצה במחשב שלכםRun it on your computer

להרצה במחשב שלכם: JUnit היא ספרייה חיצונית, ולכן הקובץ מוצג בלי הרצה. בפרויקט Maven או Gradle שמים אותו ב-src/test/java ומריצים mvn test.

Run it on your computer: JUnit is an external library, so the file is shown without running. In a Maven or Gradle project it goes in src/test/java and runs with mvn test.

04הצעד של היום בפרויקט מדףToday's step in the Shelf project

כתבו שלוש בדיקות למדף בתור מתודות עם שמות של 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).

טיפTip

את הצעד הזה כותבים בעמוד התרגול (התרגיל המסומן כצעד בפרויקט). בעמוד הפתרונות יש פתרון מלא עם סימולציה שמריצה אותו.

You write this step on the practice page (the exercise marked as a project step). The solutions page has a full solution with a simulation that runs it.

סיימתם את ההרצאה!Lecture complete!

עכשיו המצגת לחזרה מהירה, או ישר לתרגול.

Next: the slides for a quick review, or straight to practice.

נבנה על ידיBuilt by Ariel Yohimovich