Spring Boot REST עם בדיקותSpring Boot REST with tests
פרויקט Spring Boot, controller, service ו-repository, JSON אוטומטי, ובדיקות עם MockMvc.
A Spring Boot project, controller, service and repository, automatic JSON, and tests with MockMvc.
ראוטר קטןA tiny router
תזכורת: מה ביקשוReminder: the task
route(Request) עם switch על method + " " + path: GET /hello ו-GET /health עונים 200 עם JSON, וכל השאר 404. הדפיסו את שלוש התשובות.
route(Request) with a switch on method + " " + path: GET /hello and GET /health answer 200 with JSON, everything else 404. Print the three responses.
סימולציה: הפתרון רץ שורה אחרי שורה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 Response route(Request r) {
return switch (r.method() + " " + r.path()) {
case "GET /hello" -> new Response(200, "{\"message\": \"hello\"}");
case "GET /health" -> new Response(200, "{\"status\": \"up\"}");
default -> new Response(404, "{\"error\": \"not found\"}");
};
}
public static void main(String[] args) {
System.out.println(route(new Request("GET", "/hello", "")));
System.out.println(route(new Request("GET", "/health", "")));
System.out.println(route(new Request("GET", "/nope", "")));
}
}
record Request(String method, String path, String body) {
}
record Response(int status, String body) {
@Override
public String toString() {
return status + " " + body;
}
}
record Book(String title, String author, int year) {
String json() {
return "{\"title\": \"" + title + "\", \"author\": \"" + author + "\", \"year\": " + year + "}";
}
}200 {"message": "hello"}
200 {"status": "up"}
404 {"error": "not found"}יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
משפחות של סטטוסStatus families
תזכורת: מה ביקשוReminder: the task
status(code) לפי הספרה הראשונה: 2xx success, 4xx client error, 5xx server error. הדפיסו עבור 200, 201, 400, 404, 500.
status(code) by the first digit: 2xx success, 4xx client error, 5xx server error. Print for 200, 201, 400, 404, 500.
סימולציה: הפתרון רץ שורה אחרי שורה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 String status(int code) {
return switch (code / 100) {
case 2 -> "success";
case 4 -> "client error";
case 5 -> "server error";
default -> "other";
};
}
public static void main(String[] args) {
for (int code : new int[]{200, 201, 400, 404, 500}) {
System.out.println(code + " " + status(code));
}
}
}200 success 201 success 400 client error 404 client error 500 server error
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
שלוש שכבותThree layers
תזכורת: מה ביקשוReminder: the task
כתבו את BookRepository, BookService ו-BookController מהתזכורת. POST של Dune (201), GET של Dune (200), GET של Hamlet (404), GET של כולם (200 עם מערך).
Write BookRepository, BookService and BookController from the refresher. POST Dune (201), GET Dune (200), GET Hamlet (404), GET all (200 with an array).
סימולציה: הפתרון רץ שורה אחרי שורה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.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.StringJoiner;
public class Main {
public static void main(String[] args) {
BookController api = new BookController(new BookService(new BookRepository()));
System.out.println(api.handle(new Request("POST", "/books", "Dune;Herbert;1965")));
System.out.println(api.handle(new Request("GET", "/books/Dune", "")));
System.out.println(api.handle(new Request("GET", "/books/Hamlet", "")));
System.out.println(api.handle(new Request("GET", "/books", "")));
}
}
class BookRepository {
private final Map<String, Book> rows = new LinkedHashMap<>();
void save(Book b) {
rows.put(b.title(), b);
}
Book find(String title) {
return rows.get(title);
}
List<Book> all() {
return new ArrayList<>(rows.values());
}
}
class BookService {
private final BookRepository repo;
BookService(BookRepository repo) {
this.repo = repo;
}
Book add(String title, String author, int year) {
if (year < 0) {
throw new IllegalArgumentException("year must be >= 0");
}
Book b = new Book(title, author, year);
repo.save(b);
return b;
}
Book find(String title) {
return repo.find(title);
}
List<Book> all() {
return repo.all();
}
}
class BookController {
private final BookService service;
BookController(BookService service) {
this.service = service;
}
Response handle(Request r) {
if (r.method().equals("GET") && r.path().equals("/books")) {
StringJoiner arr = new StringJoiner(", ", "[", "]");
for (Book b : service.all()) {
arr.add(b.json());
}
return new Response(200, arr.toString());
}
if (r.method().equals("GET") && r.path().startsWith("/books/")) {
Book b = service.find(r.path().substring("/books/".length()));
return b == null ? new Response(404, "{\"error\": \"not found\"}") : new Response(200, b.json());
}
if (r.method().equals("POST") && r.path().equals("/books")) {
String[] f = r.body().split(";");
try {
return new Response(201, service.add(f[0], f[1], Integer.parseInt(f[2])).json());
} catch (IllegalArgumentException e) {
return new Response(400, "{\"error\": \"" + e.getMessage() + "\"}");
}
}
return new Response(405, "{\"error\": \"method not allowed\"}");
}
}
record Request(String method, String path, String body) {
}
record Response(int status, String body) {
@Override
public String toString() {
return status + " " + body;
}
}
record Book(String title, String author, int year) {
String json() {
return "{\"title\": \"" + title + "\", \"author\": \"" + author + "\", \"year\": " + year + "}";
}
}201 {"title": "Dune", "author": "Herbert", "year": 1965}
200 {"title": "Dune", "author": "Herbert", "year": 1965}
404 {"error": "not found"}
200 [{"title": "Dune", "author": "Herbert", "year": 1965}]יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
400 ולא חריגה400, not an exception
תזכורת: מה ביקשוReminder: the task
add(body) מקבלת title;author;year. חסר שדה: 400 {"error": "expected title;author;year"}. שנה לא מספרית: 400 {"error": "year must be a number"}. אחרת 201 עם JSON.
add(body) takes title;author;year. A missing field: 400 {"error": "expected title;author;year"}. A non-numeric year: 400 {"error": "year must be a number"}. Otherwise 201 with JSON.
סימולציה: הפתרון רץ שורה אחרי שורה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 Response add(String body) {
String[] f = body.split(";");
if (f.length != 3) {
return new Response(400, "{\"error\": \"expected title;author;year\"}");
}
int year;
try {
year = Integer.parseInt(f[2]);
} catch (NumberFormatException e) {
return new Response(400, "{\"error\": \"year must be a number\"}");
}
return new Response(201, new Book(f[0], f[1], year).json());
}
public static void main(String[] args) {
System.out.println(add("Dune;Herbert;1965"));
System.out.println(add("Dune;Herbert"));
System.out.println(add("Dune;Herbert;19x5"));
}
}
record Request(String method, String path, String body) {
}
record Response(int status, String body) {
@Override
public String toString() {
return status + " " + body;
}
}
record Book(String title, String author, int year) {
String json() {
return "{\"title\": \"" + title + "\", \"author\": \"" + author + "\", \"year\": " + year + "}";
}
}201 {"title": "Dune", "author": "Herbert", "year": 1965}
400 {"error": "expected title;author;year"}
400 {"error": "year must be a number"}יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
מדף, צעד 40: API למדףShelf, step 40: an API for the shelf
תזכורת: מה ביקשוReminder: the task
הרחיבו את השכבות: POST עם שנה שלילית מחזיר 400 (ה-service זורק, ה-controller ממיר ל-400), ושיטה לא מוכרת (DELETE) מחזירה 405. הפלט: 201, 200, 404, 400, 201, 200 עם שני ספרים, 405.
Extend the layers: a POST with a negative year returns 400 (the service throws, the controller turns it into 400), and an unknown method (DELETE) returns 405. The output: 201, 200, 404, 400, 201, 200 with two books, 405.
סימולציה: הפתרון רץ שורה אחרי שורה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.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.StringJoiner;
public class Main {
public static void main(String[] args) {
BookController api = new BookController(new BookService(new BookRepository()));
System.out.println(api.handle(new Request("POST", "/books", "Dune;Herbert;1965")));
System.out.println(api.handle(new Request("GET", "/books/Dune", "")));
System.out.println(api.handle(new Request("GET", "/books/Hamlet", "")));
System.out.println(api.handle(new Request("POST", "/books", "Old;Nobody;-5")));
System.out.println(api.handle(new Request("POST", "/books", "Emma;Austen;1815")));
System.out.println(api.handle(new Request("GET", "/books", "")));
System.out.println(api.handle(new Request("DELETE", "/books/Dune", "")));
}
}
class BookRepository {
private final Map<String, Book> rows = new LinkedHashMap<>();
void save(Book b) {
rows.put(b.title(), b);
}
Book find(String title) {
return rows.get(title);
}
List<Book> all() {
return new ArrayList<>(rows.values());
}
}
class BookService {
private final BookRepository repo;
BookService(BookRepository repo) {
this.repo = repo;
}
Book add(String title, String author, int year) {
if (year < 0) {
throw new IllegalArgumentException("year must be >= 0");
}
Book b = new Book(title, author, year);
repo.save(b);
return b;
}
Book find(String title) {
return repo.find(title);
}
List<Book> all() {
return repo.all();
}
}
class BookController {
private final BookService service;
BookController(BookService service) {
this.service = service;
}
Response handle(Request r) {
if (r.method().equals("GET") && r.path().equals("/books")) {
StringJoiner arr = new StringJoiner(", ", "[", "]");
for (Book b : service.all()) {
arr.add(b.json());
}
return new Response(200, arr.toString());
}
if (r.method().equals("GET") && r.path().startsWith("/books/")) {
Book b = service.find(r.path().substring("/books/".length()));
return b == null ? new Response(404, "{\"error\": \"not found\"}") : new Response(200, b.json());
}
if (r.method().equals("POST") && r.path().equals("/books")) {
String[] f = r.body().split(";");
try {
return new Response(201, service.add(f[0], f[1], Integer.parseInt(f[2])).json());
} catch (IllegalArgumentException e) {
return new Response(400, "{\"error\": \"" + e.getMessage() + "\"}");
}
}
return new Response(405, "{\"error\": \"method not allowed\"}");
}
}
record Request(String method, String path, String body) {
}
record Response(int status, String body) {
@Override
public String toString() {
return status + " " + body;
}
}
record Book(String title, String author, int year) {
String json() {
return "{\"title\": \"" + title + "\", \"author\": \"" + author + "\", \"year\": " + year + "}";
}
}201 {"title": "Dune", "author": "Herbert", "year": 1965}
200 {"title": "Dune", "author": "Herbert", "year": 1965}
404 {"error": "not found"}
400 {"error": "year must be >= 0"}
201 {"title": "Emma", "author": "Austen", "year": 1815}
200 [{"title": "Dune", "author": "Herbert", "year": 1965}, {"title": "Emma", "author": "Austen", "year": 1815}]
405 {"error": "method not allowed"}יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
בדיקה עם repository מזויףA test with a fake repository
תזכורת: מה ביקשוReminder: the task
FakeRepository יורשת מ-BookRepository וסופרת שמירות. בנו את ה-controller מעליה, שלחו POST תקין ו-POST עם שנה שלילית, והדפיסו true true saves=1 (הבקשה הרעה לא הגיעה לאחסון).
FakeRepository extends BookRepository and counts saves. Build the controller over it, send a good POST and a POST with a negative year, and print true true saves=1 (the bad request never reached storage).
סימולציה: הפתרון רץ שורה אחרי שורה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.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.StringJoiner;
public class Main {
public static void main(String[] args) {
FakeRepository fake = new FakeRepository();
BookController api = new BookController(new BookService(fake));
Response created = api.handle(new Request("POST", "/books", "Dune;Herbert;1965"));
Response bad = api.handle(new Request("POST", "/books", "Old;Nobody;-5"));
System.out.println((created.status() == 201) + " " + (bad.status() == 400) + " saves=" + fake.saves);
}
}
class BookRepository {
private final Map<String, Book> rows = new LinkedHashMap<>();
void save(Book b) {
rows.put(b.title(), b);
}
Book find(String title) {
return rows.get(title);
}
List<Book> all() {
return new ArrayList<>(rows.values());
}
}
class BookService {
private final BookRepository repo;
BookService(BookRepository repo) {
this.repo = repo;
}
Book add(String title, String author, int year) {
if (year < 0) {
throw new IllegalArgumentException("year must be >= 0");
}
Book b = new Book(title, author, year);
repo.save(b);
return b;
}
Book find(String title) {
return repo.find(title);
}
List<Book> all() {
return repo.all();
}
}
class FakeRepository extends BookRepository {
int saves = 0;
@Override
void save(Book b) {
saves++;
super.save(b);
}
}
class BookController {
private final BookService service;
BookController(BookService service) {
this.service = service;
}
Response handle(Request r) {
if (r.method().equals("GET") && r.path().equals("/books")) {
StringJoiner arr = new StringJoiner(", ", "[", "]");
for (Book b : service.all()) {
arr.add(b.json());
}
return new Response(200, arr.toString());
}
if (r.method().equals("GET") && r.path().startsWith("/books/")) {
Book b = service.find(r.path().substring("/books/".length()));
return b == null ? new Response(404, "{\"error\": \"not found\"}") : new Response(200, b.json());
}
if (r.method().equals("POST") && r.path().equals("/books")) {
String[] f = r.body().split(";");
try {
return new Response(201, service.add(f[0], f[1], Integer.parseInt(f[2])).json());
} catch (IllegalArgumentException e) {
return new Response(400, "{\"error\": \"" + e.getMessage() + "\"}");
}
}
return new Response(405, "{\"error\": \"method not allowed\"}");
}
}
record Request(String method, String path, String body) {
}
record Response(int status, String body) {
@Override
public String toString() {
return status + " " + body;
}
}
record Book(String title, String author, int year) {
String json() {
return "{\"title\": \"" + title + "\", \"author\": \"" + author + "\", \"year\": " + year + "}";
}
}true true saves=1
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
דפדוףPaging
תזכורת: מה ביקשוReminder: the task
page(titles, page, size) מחזירה JSON עם page, items (רק הדף המבוקש) ו-total. עבור 5 כותרים ו-size 2: דף 0 ["Dune", "Emma"], דף 2 ["Solaris"], דף 9 [].
page(titles, page, size) returns JSON with page, items (only the requested page) and total. For 5 titles and size 2: page 0 ["Dune", "Emma"], page 2 ["Solaris"], page 9 [].
סימולציה: הפתרון רץ שורה אחרי שורה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.List;
import java.util.stream.Collectors;
public class Main {
static String page(List<String> titles, int page, int size) {
int from = Math.min(page * size, titles.size());
int to = Math.min(from + size, titles.size());
String items = titles.subList(from, to).stream().map(t -> "\"" + t + "\"").collect(Collectors.joining(", ", "[", "]"));
return "{\"page\": " + page + ", \"items\": " + items + ", \"total\": " + titles.size() + "}";
}
public static void main(String[] args) {
List<String> all = List.of("Dune", "Emma", "Ulysses", "Persuasion", "Solaris");
System.out.println(page(all, 0, 2));
System.out.println(page(all, 2, 2));
System.out.println(page(all, 9, 2));
}
}{"page": 0, "items": ["Dune", "Emma"], "total": 5}
{"page": 2, "items": ["Solaris"], "total": 5}
{"page": 9, "items": [], "total": 5}יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.