0Pricing
Testing Mastery: JUnit, Mockito & Integration Tests · Урок

Проверки и выполнение в JUnit

Научитесь использовать методы проверок JUnit для проверки результатов тестов и эффективно запускать тесты в своей среде разработки.

«Проверки и выполнение в JUnit» — бесплатный урок Testing Mastery: JUnit, Mockito & Integration Tests на CoddyKit. Это урок 3 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения Testing Mastery: JUnit, Mockito & Integration Tests, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс Testing Mastery: JUnit, Mockito & Integration Tests содержит 4 уроков всего.

Части этого урока еще не переведены и отображаются на английском.

What are Assertions?

Assertions are the checks that decide pass or fail: they verify a condition is true, and if it isn’t, the test fails and flags the problem.

Checking for Equality

assertEquals() is the workhorse: pass it the expected value and the actual value, and the test passes only when they match.

`assertEquals` in Action

Here’s assertEquals verifying a sum: compare the expected result against what your method returns. Match means pass.

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

public class MathUtilsTest {

    // A simple method to test
    int add(int a, int b) {
        return a + b;
    }

    @Test
    void testAddMethod() {
        // Expected result: 5
        int expected = 5;
        // Actual result from our method
        int actual = add(2, 3);
        
        // Assert that expected and actual are the same
        assertEquals(expected, actual, "2 + 3 should be 5");
    }
}

Checking Boolean Conditions

To check logical outcomes, use assertTrue and assertFalse — they pass when the condition is true or false respectively.

`assertTrue` in Practice

Here assertTrue confirms a number is positive — a clean way to validate any boolean condition.

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

public class NumberCheckerTest {

    // A simple method to test
    boolean isPositive(int number) {
        return number > 0;
    }

    @Test
    void testIsPositive() {
        int num = 10;
        // Assert that num is positive
        assertTrue(isPositive(num), num + " should be positive");
    }
}

Handling Null Values

For null checks, use assertNotNull and assertNull — crucial for catching NullPointerExceptions before they bite.

`assertNotNull` Demo

Here assertNotNull and assertNull verify a lookup that returns a user or null when none is found.

import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;

public class UserServiceTest {

    // Dummy method simulating fetching a user
    String getUserById(int id) {
        if (id == 1) {
            return "Alice"; // User found
        }
        return null; // User not found
    }

    @Test
    void testExistingUser() {
        String user = getUserById(1);
        assertNotNull(user, "User with ID 1 should exist");
    }

    @Test
    void testNonExistingUser() {
        String user = getUserById(99);
        assertNull(user, "User with ID 99 should not exist");
    }
}

Executing JUnit Tests

Running tests is easy: most IDEs have built-in JUnit support — right-click a class or method, hit Run, and read the results window.

Understanding Pass/Fail

Reading results is simple: green means all tests passed, red means an assertion failed and there’s likely a bug. Click a failure for details.

Assertion Challenge

Consider the following simple method and test. What will be the outcome of running this test?

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

public class SimpleCalculatorTest {
    int subtract(int a, int b) {
        return a - b;
    }

    @Test
    void testSubtract() {
        assertEquals(10, subtract(15, 5));
    }
}

Recap: Assertions & Execution

You can now validate code with JUnit assertions — assertEquals, assertTrue, assertNull and friends — and run tests right in your IDE.

Часто задаваемые вопросы

Урок «Проверки и выполнение в JUnit» бесплатный?

Да — полный текст урока «Проверки и выполнение в JUnit» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс Testing Mastery: JUnit, Mockito & Integration Tests, подпишись на CoddyKit PRO. Курс Testing Mastery: JUnit, Mockito & Integration Tests содержит 4 уроков всего.

Чему я научусь в уроке «Проверки и выполнение в JUnit»?

Научитесь использовать методы проверок JUnit для проверки результатов тестов и эффективно запускать тесты в своей среде разработки. Ты практикуешь Testing Mastery: JUnit, Mockito & Integration Tests с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.

Нужен ли мне опыт, чтобы начать Testing Mastery: JUnit, Mockito & Integration Tests?

Предыдущий опыт не требуется. Testing Mastery: JUnit, Mockito & Integration Tests на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 3 из 4.

Сколько времени занимает урок «Проверки и выполнение в JUnit»?

Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.

Можно ли писать и запускать код в этом уроке Testing Mastery: JUnit, Mockito & Integration Tests?

Да. Каждый урок Testing Mastery: JUnit, Mockito & Integration Tests включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.

Все уроки этого курса

  1. Знакомство с модульным тестированием
  2. Основные аннотации JUnit 5
  3. Проверки и выполнение в JUnit
  4. Организация тестов с помощью @DisplayName и вложенности
← Назад к Testing Mastery: JUnit, Mockito & Integration Tests