0Pricing
Spring Boot 4 Microservices & REST APIs · درس

اختبار الوحدات باستخدام JUnit وMockito

اختبر المكوّنات بمعزل عن بعضها

اختبار الوحدات باستخدام JUnit وMockito درس مجاني في Spring Boot 4 Microservices & REST APIs على CoddyKit. هذا هو الدرس 1 من أصل 4. يمكنك قراءة الدرس كاملاً أدناه مجاناً — ثم تمرن عليه مباشرة في المتصفح باستخدام محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7. هذا الدرس جزء من مسار التعلم في Spring Boot 4 Microservices & REST APIs، وتقدمك يتزامن عبر الويب وتطبيق CoddyKit. تتضمن دورة Spring Boot 4 Microservices & REST APIs 4 دروس في المجموع.

بعض أجزاء هذا الدرس لم تُترجم بعد وتظهر باللغة الإنجليزية.

Why Unit Tests

A unit test verifies a single class in isolation, with its collaborators replaced by fakes.

  • Fast — no Spring context, no database
  • Focused — tests one piece of logic
  • Reliable — no external dependencies

JUnit 5 Basics

Spring Boot uses JUnit 5 (Jupiter). A test is a method annotated with @Test.

import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;

class CalculatorTest {
    @Test
    void addsTwoNumbers() {
        assertEquals(5, 2 + 3);
    }
}

Lifecycle Annotations

Use @BeforeEach to set up state before each test and @AfterEach to clean up.

@BeforeEach
void setUp() {
    calculator = new Calculator();
}

@Test
void addsCorrectly() {
    assertEquals(7, calculator.add(3, 4));
}

AssertJ Fluent Assertions

Spring Boot bundles AssertJ for readable assertions with assertThat.

import static org.assertj.core.api.Assertions.assertThat;

assertThat(result).isEqualTo(42);
assertThat(list).hasSize(3).contains("a");

What is Mockito

Mockito creates mock objects — fake implementations of dependencies whose behavior you control.

This lets you test a class without its real collaborators (database, HTTP clients, etc.).

Creating Mocks

Annotate the test class with @ExtendWith(MockitoExtension.class). Use @Mock for dependencies and @InjectMocks for the class under test.

@ExtendWith(MockitoExtension.class)
class UserServiceTest {
    @Mock
    UserRepository repository;

    @InjectMocks
    UserService service;
}

Stubbing with when/thenReturn

Define a mock's behavior with when(...).thenReturn(...).

@Test
void returnsUserById() {
    User alice = new User("1", "Alice");
    when(repository.findById("1"))
        .thenReturn(Optional.of(alice));

    User result = service.getById("1");

    assertThat(result.getName()).isEqualTo("Alice");
}

Throwing from a Mock

Use thenThrow to simulate error conditions.

when(repository.findById("99"))
    .thenThrow(new RuntimeException("DB down"));

assertThrows(RuntimeException.class,
    () -> service.getById("99"));

Verifying Interactions

verify checks that a mock method was called with expected arguments.

@Test
void savesUser() {
    service.create(new User("2", "Bob"));

    verify(repository).save(any(User.class));
    verify(repository, times(1)).save(any());
}

Argument Matchers

Matchers like any(), eq(), and anyString() make stubs flexible.

when(repository.findByName(anyString()))
    .thenReturn(List.of(new User("1", "Alice")));

verify(repository).deleteById(eq("1"));

Capturing Arguments

ArgumentCaptor captures the value passed to a mock so you can assert on it.

ArgumentCaptor<User> captor =
    ArgumentCaptor.forClass(User.class);
verify(repository).save(captor.capture());
assertThat(captor.getValue().getName())
    .isEqualTo("Bob");

Quick Check

Test your understanding of Mockito.

Recap

You learned to write fast unit tests:

  • JUnit 5 with @Test, @BeforeEach
  • AssertJ assertThat for readable checks
  • Mockito @Mock / @InjectMocks
  • when/thenReturn to stub, verify to confirm calls

الأسئلة الشائعة

هل درس «اختبار الوحدات باستخدام JUnit وMockito» مجاني؟

نعم — نص درس «اختبار الوحدات باستخدام JUnit وMockito» كامل متاح مجاناً هنا على الويب. لتمرينه بشكل تفاعلي (محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7) وفتح باقي دورة Spring Boot 4 Microservices & REST APIs، انتقل إلى CoddyKit PRO. تتضمن دورة Spring Boot 4 Microservices & REST APIs 4 دروس في المجموع.

ماذا ستتعلم في «اختبار الوحدات باستخدام JUnit وMockito»؟

اختبر المكوّنات بمعزل عن بعضها تتمرن على Spring Boot 4 Microservices & REST APIs مع أكواد عملية تشغلها مباشرة في المتصفح، ومدرس ذكاء اصطناعي متاح 24/7 يجيب على أسئلتك أثناء عملك.

هل أحتاج إلى خبرة سابقة لأبدأ Spring Boot 4 Microservices & REST APIs؟

لا تُشترط خبرة سابقة. Spring Boot 4 Microservices & REST APIs على CoddyKit منظم للمبتدئين حتى المتقدمين، لذا يمكنك البدء من هنا أو من البداية والتقدم بسرعتك الخاصة. هذا هو الدرس 1 من أصل 4.

كم من الوقت يستغرق درس «اختبار الوحدات باستخدام JUnit وMockito»؟

معظم دروس CoddyKit تستغرق حوالي 5–10 دقائق. كل منها موجز وتفاعلي، لذا تحرز تقدماً مستمراً وتستأنف من حيث توقفت عبر الويب والتطبيق.

هل يمكنني كتابة وتشغيل أكواد في درس Spring Boot 4 Microservices & REST APIs هذا؟

نعم. كل درس في Spring Boot 4 Microservices & REST APIs يتضمن محرر أكواد مدمج، لذا تكتب وتشغل أكواداً حقيقية مباشرة في متصفحك وتحصل على تعليقات فورية من الذكاء الاصطناعي — بدون إعداد محلي.

جميع الدروس في هذه الدورة

  1. اختبار الوحدات باستخدام JUnit وMockito
  2. اختبارات طبقة الويب باستخدام MockMvc
  3. اختبارات التكامل باستخدام @SpringBootTest
  4. التبعيات الحقيقية باستخدام Testcontainers
← العودة إلى Spring Boot 4 Microservices & REST APIs