모의 객체, 스텁 및 테스트 데이터
코드 의존성을 격리하고 모의 객체와 스텁을 사용하며 테스트 데이터를 효율적으로 관리하는 기법을 배웁니다.
모의 객체, 스텁 및 테스트 데이터은(는) CoddyKit의 무료 Elixir & Phoenix: Scalable Backend Development 강의입니다. 이것은 4개 중 3번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 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
Moxlibrary 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 AI 튜터), CoddyKit PRO로 업그레이드하면 Elixir & Phoenix: Scalable Backend Development 강의 전체를 잠금 해제할 수 있습니다. Elixir & Phoenix: Scalable Backend Development 강의에는 총 4개의 강의가 포함되어 있습니다.
“모의 객체, 스텁 및 테스트 데이터”에서 뭘 배우나요?
코드 의존성을 격리하고 모의 객체와 스텁을 사용하며 테스트 데이터를 효율적으로 관리하는 기법을 배웁니다. 브라우저에서 직접 실행하는 실습 코드로 Elixir & Phoenix: Scalable Backend Development을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
Elixir & Phoenix: Scalable Backend Development을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 Elixir & Phoenix: Scalable Backend Development은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 3번째 강의입니다.
“모의 객체, 스텁 및 테스트 데이터” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Elixir & Phoenix: Scalable Backend Development 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Elixir & Phoenix: Scalable Backend Development 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- ExUnit을 활용한 단위 테스트
- Phoenix 애플리케이션 통합 테스트
- 모의 객체, 스텁 및 테스트 데이터
- StreamData를 사용한 속성 기반 테스트