0Pricing
Elixir & Phoenix: Scalable Backend Development · Урок

Моки, заглушки и тестовые данные

Изучите методы изоляции зависимостей кода, использования моков и заглушек, а также эффективного управления тестовыми данными.

«Моки, заглушки и тестовые данные» — бесплатный урок Elixir & Phoenix: Scalable Backend Development на CoddyKit. Это урок 3 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения Elixir & Phoenix: Scalable Backend Development, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс Elixir & Phoenix: Scalable Backend Development содержит 4 уроков всего.

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

Why Isolate Dependencies?

In real-world applications, your code often relies on other components or external services. These are called dependencies.

Imagine your application needs to:

  • Save data to a database.
  • Send emails via an email service.
  • Fetch data from a third-party API.

Testing these directly can be slow, unreliable (what if the API is down?), or costly. We need a way to test our code in isolation.

Understanding Test Doubles

When testing code that interacts with external services or complex components, we often use test doubles. These are generic objects that stand in for real dependencies during a test.

Common types include:

  • Stubs: Provide predefined answers to method calls.
  • Mocks: Verify that certain actions (method calls) occurred.
  • Fakes: Lightweight working implementations (e.g., an in-memory database).

In this lesson, we'll focus on Stubs and Mocks, primarily using the Mox library.

What's a Stub?

A stub is a stand-in for a real dependency that provides pre-programmed responses to method calls. It's like a script for a supporting actor: when your code 'asks' the stub something, the stub simply gives a canned answer.

Stubs help you control the environment your code is tested in, ensuring consistent results without external side effects.

Try this example to see the concept:

defmodule Notifier do
  @callback send_notification(message :: String.t) :: :ok
end

defmodule RealNotifier do
  @behaviour Notifier
  def send_notification(message) do
    IO.puts("Real Notifier sent: #{message}")
    :ok
  end
end

defmodule StubNotifier do
  @behaviour Notifier
  def send_notification(_message) do
    IO.puts("Stub Notifier received message (but didn't send for real).")
    :ok
  end
end

defmodule Client do
  def trigger_notification(message, notifier_module) do
    notifier_module.send_notification(message)
  end
end

IO.puts("--- Using Real Notifier ---")
Client.trigger_notification("Hello World!", RealNotifier)

IO.puts("\n--- Using Stub Notifier in a test-like scenario ---")
Client.trigger_notification("Test Message", StubNotifier)

Introducing Mox for Stubbing

In Elixir, the Mox library is a popular choice for creating mocks and stubs. It integrates well with ExUnit and helps ensure your test doubles conform to defined behaviours.

First, you define a mock module using Mox.defmock/2, specifying the behaviour it should implement. This acts as a proxy for your real module.

# In test/support/mocks.ex
defmodule MyApp.NotifierMock do
  use Mox

  # This mock will implement the MyApp.Notifier behaviour
  # (Assuming MyApp.Notifier defines @callback notify/1)
  @behaviour MyApp.Notifier
end

# In test_helper.exs, you'd typically define:
# Mox.defmock(MyApp.NotifierMock, for: MyApp.Notifier)

Stubbing Responses with Mox

Once your mock module is defined, you can use Mox.stub/3 or Mox.expect/3 (which also stubs) within your tests to define what functions should return. This allows you to simulate success or failure scenarios from your dependencies.

Mox.stub/3 takes the mock module, the function name, and a function that defines the return value based on arguments.

# Assume MyApp.NotifierMock is defined and MyApp.Client uses it.
# In an ExUnit test case:
# use Mox
# setup :verify_on_exit!

# Stub the :notify function to always return :ok
Mox.stub(MyApp.NotifierMock, :notify, fn _message ->
  IO.puts("Mox stub received message, returning :ok.")
  :ok
end)

# If MyApp.Client.send_message("Hello", MyApp.NotifierMock) is called,
# it will receive :ok as the result, without calling the real notifier.

What's a Mock?

A mock is a test double that not only provides predefined responses (like a stub) but also verifies that specific interactions occurred. It answers the question: 'Was this function called, with these arguments, and how many times?'

Mocks are useful when you want to ensure your code correctly interacts with its dependencies, for example, making sure an email was indeed sent or a specific log entry was created.

Verifying Interactions with Mox

Mox.expect/3 is used for both stubbing responses and setting expectations for function calls. If an expected call isn't made, or is made with different arguments, the test will fail.

This helps you assert the 'side effects' of your code, ensuring it communicates correctly with its dependencies.

# Assume MyApp.NotifierMock is defined and MyApp.Client uses it.
# In an ExUnit test case:
# use Mox
# setup :verify_on_exit!

# Expect :notify to be called exactly once with "Urgent Message"
Mox.expect(MyApp.NotifierMock, :notify, fn "Urgent Message" ->
  IO.puts("Mox mock received expected message: Urgent Message")
  :ok
end)

# If MyApp.Client.send_message("Urgent Message", MyApp.NotifierMock) is called,
# the expectation is met. If not, the test fails at the end.

Managing Test Data

Beyond isolating dependencies, managing test data is crucial. Hardcoding data directly in tests can lead to:

  • Brittleness: Changing a schema or constraint breaks many tests.
  • Repetition: Copy-pasting complex data structures.
  • Inconsistency: Tests relying on different, potentially invalid, data.

We need a better way to generate realistic and valid data for our tests.

Test Data Factories

Test data factories are functions or modules designed to generate valid, customizable data for your tests. Instead of manually creating maps or structs, you call a factory function.

This approach makes your tests:

  • Robust: Factories handle defaults and ensure validity.
  • Flexible: You can override specific attributes as needed.
  • Concise: Less boilerplate for data creation in tests.

Here's a simple factory example:

defmodule UserFactory do
  def build_user(attrs \\ %{}) do
    defaults = %{
      id: "user-#{:rand.uniform(100000)}",
      name: "User Name #{:rand.uniform(100)}",
      email: "user#{:rand.uniform(100)}@example.com",
      age: :rand.uniform(50) + 18
    }
    Map.merge(defaults, attrs)
  end
end

user1 = UserFactory.build_user()
IO.puts("Generated User 1:")
IO.inspect(user1)

user2 = UserFactory.build_user(%{name: "Alice", email: "alice@example.com"})
IO.puts("\nGenerated User 2 (customized):")
IO.inspect(user2)

Quick Check

You've learned about stubs, mocks, and how to manage test data. Let's test your understanding of the core concepts.

Recap & Next Steps

In this lesson, we explored crucial techniques for writing more effective and isolated tests:

  • We learned about test doubles, specifically stubs (for predefined responses) and mocks (for verifying interactions).
  • We saw how the Mox library helps implement these concepts in Elixir, especially when working with behaviours.
  • Finally, we discussed strategies for managing test data using factories to create robust and flexible test environments.

These tools are essential for building reliable Elixir and Phoenix applications. Keep practicing to master them!

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

Урок «Моки, заглушки и тестовые данные» бесплатный?

Да — полный текст урока «Моки, заглушки и тестовые данные» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс Elixir & Phoenix: Scalable Backend Development, подпишись на CoddyKit PRO. Курс Elixir & Phoenix: Scalable Backend Development содержит 4 уроков всего.

Чему я научусь в уроке «Моки, заглушки и тестовые данные»?

Изучите методы изоляции зависимостей кода, использования моков и заглушек, а также эффективного управления тестовыми данными. Ты практикуешь Elixir & Phoenix: Scalable Backend Development с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.

Нужен ли мне опыт, чтобы начать Elixir & Phoenix: Scalable Backend Development?

Предыдущий опыт не требуется. Elixir & Phoenix: Scalable Backend Development на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 3 из 4.

Сколько времени занимает урок «Моки, заглушки и тестовые данные»?

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

Можно ли писать и запускать код в этом уроке Elixir & Phoenix: Scalable Backend Development?

Да. Каждый урок Elixir & Phoenix: Scalable Backend Development включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.

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

  1. Модульное тестирование с ExUnit
  2. Интеграционное тестирование приложений Phoenix
  3. Моки, заглушки и тестовые данные
  4. Тестирование на основе свойств с помощью StreamData
← Назад к Elixir & Phoenix: Scalable Backend Development