
One of the first steps when I'm starting to learn a new programming language is to figure out how to do unit testing in that language. We are all wired differently, but unit testing is a perfect tool to experiment/testing syntax, features, scopes, and about everything in a programming language.
I recently picked up and started to play withOCaml and it has an awsomeREPL (calledtoplevel) tool which is a great substitute for unit tests to learn and testing the OCaml language for those that prefer that instead.
However lets try to set up a simple project with some unit tests withOunit2. This assumes that OCaml with the build systemDune is installed.
# Create projectdune init proj unit_test_examplecdunit_test_example# Install the OUnti2 testing frameworkopaminstallounit2# Open the IDEcode.
Navigate to the file,main.ml, should be located in thebin directory.
Replace the current code in main.ml with this.
let()=matchSys.argvwith|[|_;n|]->Unit_test_example.Factorial.factorial(int_of_stringn)|>print_int;print_newline()|_->print_endline"Usage: unit_test_example [n]";exit64
The code above wants to use a function,factorial, that is defined in a module calledFactorial. Jump to thelib directory and create the file,factorial.ml, there to start to solve that issue.
In that file we will create the code that we want to test.
letrecfactorialn=matchnwith|0|1->1|_->n*factorial(n-1)
Now it's time to create our tests for the factorial code. Open the file,unit_test_example.ml in the test directory and paste following code into that file.
openOUnit2lettest_factorial_of_zero_=assert_equal1(Unit_test_example.Factorial.factorial0)lettest_factorial_of_five_=assert_equal120(Unit_test_example.Factorial.factorial5)let()=run_test_tt_main("factorial tests">:::["factorial of zero">::test_factorial_of_zero;"factorial of five">::test_factorial_of_five;])
Here we create two simple tests that asserts the expected value for factorial zero and five. The entry function,let (), is then calling our test functions. Before we are able to run our unit tests we will need to configure our dune file to recognize the lib file,factorial.ml, first. Do this by open the filedune that is located in the test directory.
This file should look like this.
(test(nameunit_test_example)(librariesounit2unit_test_example))
The third line is added to configure that the test library is aware of theOunit2 library and ourunit_test_example library.
We are now ready to run our unit tests.
Now we have something to tinker with to explore the OCaml land.
And if you would like to run the program from the CLI you can execute it like this.
# Where 5 is the factorial to calculateduneexec ./bin/main.exe-- 5
Happy testing!
Top comments(0)
For further actions, you may consider blocking this person and/orreporting abuse