ballerina-lang icon indicating copy to clipboard operation
ballerina-lang copied to clipboard

[Improvement]: Improve the test code generated for service template

Open TharmiganK opened this issue 1 year ago • 0 comments

Description

The generated test code for the ballerina service template(bal new -t service myService) can be improved

Describe your problem(s)

The generated test code looks like this:

import ballerina/http;
import ballerina/io;
import ballerina/test;

http:Client testClient = check new ("http://localhost:9090");

// Before Suite Function

@test:BeforeSuite
function beforeSuiteFunc() {
    io:println("I'm the before suite function!");
}

// Test function

@test:Config {}
function testServiceWithProperName() {
    string|error response = testClient->get("/greeting/?name=John");
    test:assertEquals(response, "Hello, John");
}

// Negative test function

@test:Config {}
function testServiceWithEmptyName() returns error? {
    http:Response response = check testClient->get("/greeting/");
    test:assertEquals(response.statusCode, 500);
    json errorPayload = check response.getJsonPayload();
    test:assertEquals(errorPayload.message, "name should not be empty!");
}

// After Suite Function

@test:AfterSuite
function afterSuiteFunc() {
    io:println("I'm the after suite function!");
}

Describe your solution(s)

The code can be improved by utilising the client resource methods:

import ballerina/http;
import ballerina/io;
import ballerina/test;

http:Client testClient = check new ("http://localhost:9090");

// Before Suite Function
@test:BeforeSuite
function beforeSuiteFunc() {
    io:println("I'm the before suite function!");
}

// Test function
@test:Config {}
function testServiceWithProperName() {
    string|error response = testClient->/greeting(name = "John");
    test:assertEquals(response, "Hello, John");
}

// Negative test function
@test:Config {}
function testServiceWithEmptyName() returns error? {
    http:Response response = check testClient->/greeting;
    test:assertEquals(response.statusCode, 500);
    json errorPayload = check response.getJsonPayload();
    test:assertEquals(errorPayload.message, "name should not be empty!");
}

// After Suite Function
@test:AfterSuite
function afterSuiteFunc() {
    io:println("I'm the after suite function!");
}

Related area

-> Other Area

Related issue(s) (optional)

No response

Suggested label(s) (optional)

No response

Suggested assignee(s) (optional)

No response

TharmiganK avatar May 08 '24 03:05 TharmiganK