October 31st, 2023 - TDD with Livebook
Tests
TDD = Test Driven Development
ExUnit.start(auto_run: false)
defmodule CalculatorTest do
use ExUnit.Case, async: false
describe "Testing the addition function" do
test "2 plus 3 is 5" do
assert Calculator.add(2, 3) == 5
end
test "2 plus 2 is 4" do
assert Calculator.add(2, 2) == 4
end
end
describe "Testing the multiplication function" do
test "2 times 3 is 6" do
assert Calculator.multiply(2, 3) == 6
end
test "2 times 20 is 40" do
assert Calculator.multiply(2, 20) == 40
end
end
end
ExUnit.run()
Code
defmodule Calculator do
def add(a, b) do
a + b
end
def multiply(a, b) do
a * b
end
end
Second example
Tests
ExUnit.start(auto_run: false)
defmodule MethodTest do
use ExUnit.Case, async: false
describe "Testing the square root function" do
test "the square root of 9 is 3.0" do
assert Method.sqrt(9) == 3.0
end
test "the square root of 16 is 4.00..." do
assert Method.sqrt(16) == 4.0
end
end
describe "Testing the power function" do
test "3 raised to the power of 2 is 9" do
assert Method.pow(3, 2) == 9.0
end
end
describe "Testing the cubic root function" do
test "the cubic root of 27 is 3.0" do
assert Method.cbcrt(27) == 3.0
end
test "the cubic root of 64 is 4.0" do
assert_in_delta Method.cbcrt(64), 4.0, 0.00000000000001
end
end
end
ExUnit.run()
Code
defmodule Method do
def sqrt(x) do
x ** (1 / 2)
end
def pow(base, exponent) do
base ** exponent
end
def cbcrt(x) do
x ** (1 / 3)
end
end
Method.sqrt(16)