0Pricing
Elixir & Phoenix: Scalable Backend Development · Ders

ExUnit ile Birim Testi

Yerleşik ExUnit çatısını kullanarak Elixir modülleriniz ve işlevleriniz için hızlı ve güvenilir birim testleri yazın.

ExUnit ile Birim Testi, CoddyKit'te ücretsiz bir Elixir & Phoenix: Scalable Backend Development dersidir. Bu, 4 dersinin 1. dersidir. Aşağıdan dersin tamamını ücretsiz okuyabilir, sonra tarayıcıda yerleşik kod editörü ve 7/24 yapay zeka koçu ile uygulamalı olarak pratik yapabilirsin. Bu, Elixir & Phoenix: Scalable Backend Development öğrenme yolunun bir parçasıdır ve ilerlemeniz web ve CoddyKit uygulaması arasında senkronize olur. Elixir & Phoenix: Scalable Backend Development kursu toplamda 4 dersten oluşur.

Bu dersin bazı bölümleri henüz çevrilmemiş olup İngilizce olarak gösterilmektedir.

Intro to ExUnit

Welcome to unit testing with ExUnit! ExUnit is Elixir's built-in testing framework, designed to help you write reliable and maintainable code.

Unit tests focus on small, isolated parts of your code, like individual functions or modules. They ensure each component works as expected, giving you confidence as your application grows.

Your First ExUnit Test

Elixir test files typically end with _test.exs and are placed in a test/ directory. Inside, you use ExUnit.Case to bring in testing functionalities.

A test block starts with test "description" do ... end. Here's a simple example:

defmodule MyMath do
  def add(a, b), do: a + b
end

defmodule MyMathTest do
  use ExUnit.Case, async: true

  test "adds two numbers correctly" do
    assert MyMath.add(1, 2) == 3
  end
end

Asserting with `assert`

The most common assertion in ExUnit is assert. It checks if an expression evaluates to a truthy value (anything other than false or nil).

You often use it to compare expected outcomes with actual results.

defmodule Calculator do
  def multiply(a, b), do: a * b
end

defmodule CalculatorTest do
  use ExUnit.Case, async: true

  test "multiplies positive numbers" do
    assert Calculator.multiply(2, 3) == 6
  end

  test "multiplies by zero" do
    assert Calculator.multiply(5, 0) == 0
  end
end

Refuting with `refute`

Sometimes, you want to ensure something is not true. That's where refute comes in. It's the opposite of assert.

refute passes if its argument evaluates to a falsy value (false or nil).

defmodule Validator do
  def is_negative(num), do: num < 0
end

defmodule ValidatorTest do
  use ExUnit.Case, async: true

  test "refutes positive numbers as negative" do
    refute Validator.is_negative(10)
    refute Validator.is_negative(0)
  end

  test "asserts negative numbers" do
    assert Validator.is_negative(-5)
  end
end

Testing for Exceptions

What if your function is supposed to raise an error under specific conditions? assert_raise lets you test for that!

You provide the expected exception type and an optional message, along with a function that should trigger the error.

defmodule Divider do
  def divide(a, b) do
    if b == 0, do: raise(ArgumentError, "Cannot divide by zero"), else: a / b
  end
end

defmodule DividerTest do
  use ExUnit.Case, async: true

  test "raises ArgumentError for division by zero" do
    assert_raise ArgumentError, "Cannot divide by zero", fn ->
      Divider.divide(10, 0)
    end
  end
end

Setting Up Test Context

Many tests need common setup, like creating a temporary resource or a mock user. ExUnit's setup callback runs before each test in a module.

It should return {:ok, assigns} where assigns is a keyword list or map that will be available in your test function's arguments.

defmodule UserProfileTest do
  use ExUnit.Case, async: true

  setup do
    # This runs before each test
    user = %{id: 101, name: "Jane Doe", email: "jane@example.com"}
    {:ok, user: user, admin: true}
  end

  test "user has a name", %{user: user} do
    assert user.name == "Jane Doe"
  end

  test "context includes admin flag", %{admin: admin_status} do
    assert admin_status == true
  end
end

Grouping Tests with `describe`

As your test files grow, you might want to logically group related tests. The describe macro helps organize tests within a module, making your test suite more readable.

You can even nest describe blocks!

defmodule StringUtils do
  def capitalize(str), do: String.capitalize(str)
  def reverse(str), do: String.reverse(str)
end

defmodule StringUtilsTest do
  use ExUnit.Case, async: true

  describe "capitalize/1" do
    test "capitalizes first letter" do
      assert StringUtils.capitalize("hello") == "Hello"
    end

    test "handles empty string" do
      assert StringUtils.capitalize("") == ""
    end
  end

  describe "reverse/1" do
    test "reverses a string" do
      assert StringUtils.reverse("world") == "dlrow"
    end
  end
end

Executing Your Tests

Once you've written your tests, running them is simple using Elixir's build tool, Mix.

  • To run all tests in your project: mix test
  • To run tests in a specific file: mix test test/my_module_test.exs
  • To run a specific test by line number: mix test test/my_module_test.exs:10
  • To run tests matching a description: mix test --only "adds two numbers"

ExUnit Challenge

Consider the following Elixir module designed to check if a number is odd. Which ExUnit assertion correctly tests if NumberChecker.is_odd(5) returns true?

defmodule NumberChecker do
  def is_odd(n) when is_integer(n) do
    rem(n, 2) != 0
  end
end

Unit Testing Summary

Great job! You've covered the fundamentals of unit testing with ExUnit.

  • ExUnit is Elixir's built-in testing framework.
  • Tests are defined in _test.exs files using use ExUnit.Case.
  • assert checks for truthy values, refute for falsy values.
  • assert_raise verifies that specific exceptions are thrown.
  • setup callbacks prepare context for your tests.
  • describe blocks help organize related tests.
  • You run tests using mix test.

These skills are crucial for building robust and reliable Elixir applications!

Sıkça Sorulan Sorular

“ExUnit ile Birim Testi” dersi ücretsiz mi?

Evet — “ExUnit ile Birim Testi” dersin tüm metni burada web'de ücretsiz olarak okunabilir. Etkileşimli olarak pratik yapmak (yerleşik kod editörü ve 7/24 yapay zeka koçu) ve Elixir & Phoenix: Scalable Backend Development kursunun geri kalanını açmak için CoddyKit PRO'ya yükselt. Elixir & Phoenix: Scalable Backend Development kursu toplamda 4 dersten oluşur.

“ExUnit ile Birim Testi” dersinde ne öğreneceğim?

Yerleşik ExUnit çatısını kullanarak Elixir modülleriniz ve işlevleriniz için hızlı ve güvenilir birim testleri yazın. Elixir & Phoenix: Scalable Backend Development ile uygulamalı kodu tarayıcıda doğrudan çalıştırarak pratik yaparsın ve 7/24 yapay zeka koçu dersi çalışırken sorularını yanıtlar.

Elixir & Phoenix: Scalable Backend Development öğrenmeye başlamak için deneyim gerekli mi?

Önceden deneyim gerekmez. CoddyKit'te Elixir & Phoenix: Scalable Backend Development, başlangıçtan ileri seviyeye kadar yapılandırıldığı için buradan başlayabilir veya başından başlayıp kendi hızında ilerleme yapabilirsin. Bu, 4 dersinin 1. dersidir.

“ExUnit ile Birim Testi” dersi ne kadar sürer?

Çoğu CoddyKit dersi yaklaşık 5–10 dakika sürer. Her biri kısa ve etkileşimli olduğu için sabit ilerleme yaparsın ve web ile uygulama arasında tam olarak bıraktığın yerden devam edebilirsin.

Bu Elixir & Phoenix: Scalable Backend Development dersinde kod yazıp çalıştırabilir miyim?

Evet. Her Elixir & Phoenix: Scalable Backend Development dersi yerleşik bir kod editörü içerir, bu sayede tarayıcıda gerçek kod yazıp çalıştırabilir ve anlık yapay zeka geri bildirimi alırsın — yerel kurulum gerekli değildir.

Bu kursun tüm dersleri

  1. ExUnit ile Birim Testi
  2. Phoenix Uygulamalarında Tümleştirme Testi
  3. Sahte Nesneler, Taslaklar ve Test Verileri
  4. StreamData ile Özellik Tabanlı Sınama
← Elixir & Phoenix: Scalable Backend Development Sayfasına Dön