What are different testing approaches and which one is the best?

Testing is an essential part of software development. The following are the approaches to test the Elixir code:

  • ExUnit
  • Test Setup
  • Test Mock

ExUnit

ExUnit is a built-in test framework in Elixir and comes with pretty much everything needed to test the code. It consists of assert and refute functions which can be modified to implement the required test functionality.

defmodule HelloWorldTest do
% ExUnit module to be modified for the test
use ExUnit.Case
doctest HelloWorld
% Definging the test function
test "the truth" do
assert '<some condition>'
end
end

Test setup

In addition to ExUnit, Elixir consists of Test Setup which runs the setup of the systems before running the tests. Test Setup consists of two macros, setup and setup_all, to implement the test. setup runs every time the test is executed, whereas setup_all is executed only once before running the module tests.

setup do
...
end
setup_all do
...
end

Test mocks

Mocks (nouns, not verbs) replaces actual dependencies with fake ones for testing purposes. Mocks defines the behavior of both the tested module and the mock module used in its place. For this, one needs to define the mock module and use it in the application environment.

Test mocks are particularly risky to implement because using them and ensuring their implementation in the test application renders the test less reliable. Hence, ExUnit is the best approach because despite its cons (code growth, no mocks, etc.), it is a built-in feature with extensive functionality.

Copyright ©2024 Educative, Inc. All rights reserved