Return to site

chatGPT: Generating Unit test with chatGPT 🤖🧪

· java,testing

ChatGPT is a computer program designed to understand and generate human-like text. It can be used for tasks such as language translation, text generation, and creating chatbots. It's a type of Artificial Intelligence model, more specifically it's a language model, that can understand and generate text.

Developers can leverage their coding skills thanks to chatGPT.

Let's see one use case: the generation of a unit test

I first ask chatGPT to generate a Java bean with this prompt (a prompt is a command to give to chatGPT):

Write a Java bean to store a postal address.
Use the Lombok annotations to have constructors, getters, setters, and builders.

chatGPT in reply gave me:

import lombok.Builder;
import lombok.Getter;
import lombok.Setter;


@Builder
@Getter
@Setter
public class Address {
    private String street;
    private String city;
    private String state;
    private String zip;
    private String country;
}

which is great ✅👍

Now, let's ask to generate the unit test with the following prompt:

Write a Junit test that tests every fields of the Java bean from the snippet below
import lombok.Builder;
import lombok.Getter;
import lombok.Setter;

@Builder
@Getter
@Setter
public class Address {
    private String street;
    private String city;
    private String state;
    private String zip;
    private String country;
}:

chatGPT replies with:

import org.junit.Test;
import static org.junit.Assert.assertEquals;


public class AddressTest {
    @Test
    public void testAddressFields() {
        Address address = Address.builder()
                .street("123 Main St")
                .city("Anytown")
                .state("CA")
                .zip("12345")
                .country("USA")
                .build();


        // Test street field
        assertEquals("123 Main St", address.getStreet());


        // Test city field
        assertEquals("Anytown", address.getCity());


        // Test state field
        assertEquals("CA", address.getState());


        // Test zip field
        assertEquals("12345", address.getZip());


        // Test country field
        assertEquals("USA", address.getCountry());
    }
}

 

which is great ✅👍

Then I pasted it to IntelliJ and it worked fine. Great job chatGPT! 👏

 

Section image

 

Check it in the video 🎬[4min]: