Phoenix 애플리케이션 통합 테스트
Phoenix 컨트롤러, 뷰 및 채널을 테스트해 웹 애플리케이션의 여러 부분이 함께 제대로 작동하는지 확인합니다.
Phoenix 애플리케이션 통합 테스트은(는) CoddyKit의 무료 Elixir & Phoenix: Scalable Backend Development 강의입니다. 이것은 4개 중 2번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Elixir & Phoenix: Scalable Backend Development 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Elixir & Phoenix: Scalable Backend Development 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
Test Web App Interactions
Welcome to integration testing for Phoenix applications! While unit tests check individual components, integration tests ensure different parts of your web application work together seamlessly.
- They simulate real user interactions.
- They cover routes, controllers, views, and channels.
- They build confidence that your app's main flows function correctly.
Simulating HTTP Requests
Phoenix.ConnTest is your primary tool for testing HTTP requests. It allows you to simulate requests (GET, POST, PUT, DELETE) to your Phoenix application without needing a live server.
We use functions like get/2, post/3, and put/3 to send requests and then assert on the resulting connection (conn).
defmodule MyPhoenixAppWeb.ExampleTest do
use ExUnit.Case, async: true
import Phoenix.ConnTest
# Assume a simple router route: get "/hello", PageController, :hello
# and PageController.hello renders a page with "Hello World"
test "can get a simple page" do
# Simulate a GET request to /hello
conn = get("/hello")
# Assert the HTTP status code
assert conn.status == 200
# Assert the response body contains "Hello World"
assert html_response(conn, 200) =~ "Hello World"
end
endTesting GET Requests
GET requests are typically used to fetch data or display pages. When testing, you'll simulate the request and then assert on the response's status code and its content.
Use html_response/2 to extract the HTML body and assert against its content using pattern matching (=~).
defmodule MyPhoenixAppWeb.PostControllerTest do
use ExUnit.Case, async: true
import Phoenix.ConnTest
# Assume we have a router route: get "/posts", PostController, :index
# And PostController.index renders a list of posts including "My First Post"
test "lists all posts on GET /posts" do
# Simulate a request to the /posts endpoint
conn = get("/posts")
# Assert that the request was successful and contains expected content
assert conn.status == 200
assert html_response(conn, 200) =~ "<h1>All Posts</h1>"
assert html_response(conn, 200) =~ "My First Post"
end
endTesting POST Requests
POST requests are often used for creating new resources or submitting form data. When testing, you'll pass parameters along with the request.
After a successful creation, controllers often redirect. Use redirected_to/1 to check the redirect path.
defmodule MyPhoenixAppWeb.PostControllerTest do
use ExUnit.Case, async: true
import Phoenix.ConnTest
# Assume we have a router route: post "/posts", PostController, :create
# This action creates a post and redirects to the index page.
test "creates a new post on POST /posts" do
post_params = %{"post" => %{"title" => "New Post", "body" => "Content"}}
# Simulate a POST request with parameters
conn = post("/posts", post_params)
# Assert that a redirect occurred to the posts index
assert redirected_to(conn) == "/posts"
end
endAsserting Rendered Content
It's crucial to verify that your views render the correct data and structure. html_response/2 allows you to get the rendered HTML as a string.
You can then use string assertions or regular expressions to check for specific text, HTML tags, or dynamic content.
defmodule MyPhoenixAppWeb.PageControllerTest do
use ExUnit.Case, async: true
import Phoenix.ConnTest
# Assume get "/dashboard" renders a page with user information
test "renders dashboard with user info" do
# For this example, we simulate a simple GET (no session handling here)
conn = get("/dashboard")
assert conn.status == 200
response_html = html_response(conn, 200)
# Check for specific elements in the rendered HTML
assert response_html =~ "<title>Dashboard</title>"
assert response_html =~ "<span>Welcome, John Doe!</span>"
assert response_html =~ ~r/Last Login: \d{4}-\d{2}-\d{2}/ # Regex for dynamic date
end
endTesting Redirects and Errors
Testing user flow is vital. Phoenix provides helpers to assert redirects and error responses:
assert_redirected_to(conn, path): Verifies a redirect to a specific path.assert_error_sent(conn, status): Checks for an HTTP error status code.json_response(conn, status): Extracts a JSON body from an API error.
defmodule MyPhoenixAppWeb.AuthControllerTest do
use ExUnit.Case, async: true
import Phoenix.ConnTest
# Assume post "/login" redirects to /dashboard on success
test "redirects after successful login" do
login_params = %{"email" => "test@example.com", "password" => "password"}
conn = post("/login", login_params)
assert redirected_to(conn) == "/dashboard"
end
# Assume post "/register" sends a 400 error for invalid data
test "sends 400 error for invalid registration" do
invalid_params = %{"email" => "bad", "password" => "short"}
conn = post("/register", invalid_params)
assert conn.status == 400
assert json_response(conn, 400) == %{"errors" => %{"email" => ["is invalid"]}}
end
endSimulating User Sessions
Many web applications rely on sessions to maintain state, like a logged-in user. In tests, you can manually manipulate the connection's session to simulate different user states.
Use build_conn/0 to create a fresh connection, then put_session/3 to add session data before making your request.
defmodule MyPhoenixAppWeb.SessionControllerTest do
use ExUnit.Case, async: true
import Phoenix.ConnTest
# Assume get "/profile" requires a user_id in the session
test "accesses profile with session data" do
# Build a connection and add a user_id to its session
conn =
build_conn()
|> put_session(:user_id, 123)
|> get("/profile")
assert conn.status == 200
assert html_response(conn, 200) =~ "User Profile for ID: 123"
end
test "redirects unauthenticated users" do
# No session data means no authenticated user
conn = get("/profile")
assert redirected_to(conn) == "/login"
end
endChannel Testing Introduction
Phoenix Channels are for real-time communication using WebSockets. Integration tests for channels verify that clients can connect, join topics, send messages, and receive broadcasts correctly.
This is crucial for chat applications, live dashboards, and any feature requiring instant updates.
Connecting to a Channel
Phoenix.ChannelTest provides functions to simulate a client connecting to your WebSocket and joining specific channel topics. The main function you'll use is subscribe_and_join/3.
It returns {:ok, pid, socket}, where socket represents the client's connection to the channel.
defmodule MyPhoenixAppWeb.ChatChannelTest do
use ExUnit.Case, async: true
use Phoenix.ChannelTest
# Assume MyPhoenixAppWeb.UserSocket is your main WebSocket module
# and it handles joining a "room:lobby" channel.
test "can join the lobby channel" do
# Simulate a client connecting and joining "room:lobby" with no params
{:ok, _pid, socket} = subscribe_and_join(MyPhoenixAppWeb.UserSocket, "room:lobby", %{})
# Assert that the socket is connected to the correct topic
assert socket.topic == "room:lobby"
# You might also assert on assigns set during the join process
# assert socket.assigns.user_id # If user_id is assigned on join
end
endSending & Receiving Channel Messages
Once connected to a channel, you can test the message flow. Use push/3 to simulate a client sending a message to the server, and assert_broadcast/2 to verify that the server broadcasts messages back to the topic.
assert_reply/3 can check replies to specific client pushes.
defmodule MyPhoenixAppWeb.ChatChannelTest do
use ExUnit.Case, async: true
use Phoenix.ChannelTest
# Assume MyPhoenixAppWeb.UserSocket handles "new_msg" events on "room:lobby"
test "broadcasts messages to the lobby" do
{:ok, _pid, socket} = subscribe_and_join(MyPhoenixAppWeb.UserSocket, "room:lobby", %{})
# Simulate pushing a message from the client
ref = push(socket, "new_msg", %{"body" => "Hello everyone!"})
# Assert that the server replied 'ok' to the push
assert_reply ref, :ok
# Assert that a message was broadcasted back to the topic
assert_broadcast "new_msg", %{"body" => "Hello everyone!"}
end
endQuick Check
Let's check your understanding of integration testing in Phoenix.
Recap: Integrated Confidence
You've learned how to write robust integration tests for your Phoenix applications!
- We covered simulating HTTP requests using
Phoenix.ConnTest. - You now know how to test GET and POST requests, assert rendered HTML, and verify redirects and errors.
- We also explored testing real-time features with
Phoenix.ChannelTest, simulating client connections and message flows.
By writing these tests, you gain confidence that your application's components work together as intended, leading to more stable and reliable web services!
자주 묻는 질문
“Phoenix 애플리케이션 통합 테스트” 강의는 무료인가요?
네 — “Phoenix 애플리케이션 통합 테스트” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Elixir & Phoenix: Scalable Backend Development 강의 전체를 잠금 해제할 수 있습니다. Elixir & Phoenix: Scalable Backend Development 강의에는 총 4개의 강의가 포함되어 있습니다.
“Phoenix 애플리케이션 통합 테스트”에서 뭘 배우나요?
Phoenix 컨트롤러, 뷰 및 채널을 테스트해 웹 애플리케이션의 여러 부분이 함께 제대로 작동하는지 확인합니다. 브라우저에서 직접 실행하는 실습 코드로 Elixir & Phoenix: Scalable Backend Development을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
Elixir & Phoenix: Scalable Backend Development을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 Elixir & Phoenix: Scalable Backend Development은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 2번째 강의입니다.
“Phoenix 애플리케이션 통합 테스트” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Elixir & Phoenix: Scalable Backend Development 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Elixir & Phoenix: Scalable Backend Development 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- ExUnit을 활용한 단위 테스트
- Phoenix 애플리케이션 통합 테스트
- 모의 객체, 스텁 및 테스트 데이터
- StreamData를 사용한 속성 기반 테스트