Search code examples
unit-testingerror-handlingballerinaballerina-swan-lake

How can I assert error values in ballerina?


I have a error type as defined below,

type ErrorDetails record {|
    string message;
    string reason;
    "HIGH"|"MEDUIM"|"LOW" severity;
    int code;
    record {} other?;
|};

type Error error<ErrorDetails>;

I want to write a test function where I need to assert error values. How can I achieve this?


Solution

  • In the Ballerina test package, there are two methods named assertExactEquals and assertEquals which you can use to assert error values or any other value types.

    • The assertExactEquals function will check whether the two values are exactly the same and check for reference equality (===).

    • The assertEquals function will only check the values are equal.

    The below example will help you to understand how this works.

    import ballerina/test;
    
    type ErrorDetails record {|
        string message;
        string reason;
        "HIGH"|"MEDUIM"|"LOW" severity;
        int code;
        record {} other?;
    |};
    
    type Error error<ErrorDetails>;
    
    @test:Config
    function testErrors(){
        Error actual1 = error("E1", message = "error1", reason = "casting", severity = "HIGH", code=12);
        Error actual2 = error("E1", message = "error1", reason = "casting", severity = "HIGH", code=12, other = {"a": 1});
    
        Error expected = error("E1", message = "error1", reason = "casting", severity = "HIGH", code=12);
        test:assertExactEquals(actual1, actual1);
        
        test:assertNotExactEquals(actual1, expected);
    
        test:assertEquals(actual1.detail(), expected.detail());
    
        test:assertNotEquals(actual2.detail(), expected.detail());
    }
    

    If you want to learn more about the Ballerina test framework please refer to this link.