أساسيات اختبار Spring
في هذه الصفحة 8 موضوعات
نص الدروس والتمارين باللغة الإنجليزية، بينما تبقى واجهة الموقع وعناوين الدروس بالعربية.
نظرة عامة
الموضوعات
- سياق اختبار Spring
- شرائح الاختبار (Test slices)
- Mockito
- MockMvc
تعلّم أولًا
3 ساعة تدريب (تقدير)
مخرجات التعلم
- Unit-test a service without Spring by passing collaborators to its constructor.
- Test a controller with
@WebMvcTestand MockMvc, including validation and error responses. - Use a basic Mockito mock for the service under a controller test.
- Explain the cost of
@SpringBootTestand when a slice is enough.
الدروس
المختبر والتمارين
Lab
JNR-016-LAB1 · Test the products feature
Outcomes: 1–4 · Time: ~3 h
- Write unit tests for
ProductServiceusing a fake or in-memory repository (found, not found, rule violation). - Write
@WebMvcTesttests forProductController:GET /products/{id}success,POST /productsvalidation failure, and not found. - Mock the service with Mockito inside the slice tests.
- Assert the JSON body and the Problem Details shape, not only the status.
- Add one
@SpringBootTestsmoke test and record the run times of both kinds.
Acceptance: tests run in seconds; no full context in controller tests; every test asserts the body or behavior.
Exercises (assessment: write the missing tests for a provided controller)
| ID | Outcome | Task |
|---|---|---|
| JNR-016-EX01 | 1 | Unit-test PricingService with constructor-passed fakes (no annotations). |
| JNR-016-EX02 | 2 | Write a MockMvc test for GET /products returning two items; assert the array length and a field. |
| JNR-016-EX03 | 2 | Write a MockMvc test where a blank name returns 400; assert the field error. |
| JNR-016-EX04 | 3 | Stub service.get(5) to throw NotFoundException and verify the 404 body; also verify the service call. |
| JNR-016-EX05 | 4 | Time a slice test versus a @SpringBootTest for the same endpoint; write two sentences on when each is right. |
| JNR-016-EX06 | 4 | Given a suite with eight @SpringBootTest classes, each with a different @MockitoBean, explain the slowness and propose a fix. |
أظهر الحلول
- EX01
var service = new PricingService(fakeRates); assertThat(service.total(...)).isEqualByComparingTo("12.00"); - EX02
mvc.perform(get("/products")).andExpect(status().isOk()).andExpect(jsonPath("$.length()").value(2)).andExpect(jsonPath("$[0].name").value("Pen")); - EX03
mvc.perform(post("/products").contentType(APPLICATION_JSON).content("{\"name\":\"\"}")).andExpect(status().isBadRequest())plus ajsonPathcheck on the errors. - EX04
when(service.get(5)).thenThrow(new NotFoundException("Product",5));then check the 404 andverify(service).get(5). - EX05 Slice: faster, tests the web layer only. Full context: slower, tests the wiring and everything together.
- EX06 Each different mock creates a new cached context; reduce them by using slices, or share one configuration or base class.
الاختبار
Outcomes: O1 plain unit tests · O2 @WebMvcTest and MockMvc · O3 basic Mockito · O4 slice vs full context.
اختبار ذاتي لك: لا توجد درجات، ولا يُحفظ أو يُرسل أي شيء. اختر إجابة ثم تحقق منها، ويمكنك المحاولة مرة أخرى كما تشاء.
الجزء العملي
Six exercises JNR-016-EX01 to EX06 plus the lab. The assessment: write the missing tests for a provided controller (success, validation failure, not found). Pass: quiz at least 8/10, the three missing tests written and passing with body assertions, lab acceptance met.
أخطاء شائعة
@SpringBootTest for everything; asserting only the status code.
التقييم
Write the missing tests for a provided controller.
الصلة بالمسار الوظيفي
Deepened in JNR-043 to JNR-047.