Test a simple function

The Ballerina language has a built-in robust test framework, which allows you to ensure that your applications are reliable. It provides support for assertions, data providers, mocking, and code coverage features, which enable programmers to write comprehensive tests.

To get started, let's set up the Ballerina package to run tests.

  1. Create a Ballerina package with the bal new command as follows.

    Copy
    $ bal new hello_world
    
  2. Create a directory in the root directory of the package named tests in which the test files will be stored.

    hello_world/
        Ballerina.toml
        main.bal
        tests/
            main_test.bal
    
  3. Create the following function in the main.bal file.

    Copy
    public function intAdd(int a, int b) returns int {
        return a + b;
    }
  4. In the main_test.bal file, make use of the test module to test out the functionality of the intAdd function in the main.bal file.

    Copy
    import ballerina/test;
    
    @test:Config
    function intAddTest() {
        test:assertEquals(intAdd(1, 3), 4);
    }
  5. Execute the tests using the following command.

    Copy
    $ bal test
    

    Then you can see the output as follows.

    Compiling source
         user/hello_world:0.1.0
    
    Running Tests
    
            hello_world
    
    
                    1 passing
                    0 failing
                    0 skipped