Skip to content

Testing with AI

Generating Unit Tests From Code

Objective

In this exercise you will create unit tests from code. To do this, we will add a new data type to Post.java and then generate the tests for it.

Here's the code snippet to add to Post.java located in dks-api/src/main/java/com/liatrio/dojo/devopsknowledgeshareapi/:

    private String dateUpdated;

    public void setDateUpdated(Date dateAsDate) {
        DateFormat dateFormat = new SimpleDateFormat(dateFormat());
        this.dateUpdated = dateFormat.format(dateAsDate);
    }

    public String getDateUpdated() {
        return dateUpdated;
    }

Let's use inline Copilot to generate the tests for this method. To do this we can,

Steps

  1. Highlight the setDatePosted and getDateUpdated methods
  2. Open the inline Copilot Prompt

    Mac: cmd ⌘ + i

    Win: ctrl + i

  3. Type Generate tests for these methods

    Copilot will prompt you with where you want to add these tests. It will try to determine where to add them for you, and display the proposed location in the Refactor Preview in VSCode.

    testing-with-ai-1

  4. If Copilot correctly suggested PostTest.java, click the apply button

  5. Run the tests

    docker run -e GRADLE_USER_HOME='/app/.gradle' -e SPRING_PROFILES_ACTIVE=local --rm -v "$(PWD)":/app -w /app eclipse-temurin:17-jdk ./gradlew --info --no-daemon build
    
    make build
    
  6. View the test results in the console or open the test report (./build/reports/tests/test/index.html) in a browser

The tests may need some additional work. Make sure to review them and make any necessary changes. Copilot can be useful for refactoring tests that are close to what you need, but may not be perfect, as well as explaining errors that are being displayed.

Tips

Use mock objects: When testing methods that interact with the database, it's a good practice to use mock objects. This allows you to isolate the method you're testing and ensure that any changes to the database during testing don't affect your actual data.

Test for edge cases: Don't just test for the "happy path". Make sure your tests cover edge cases as well. Check if Copilot has generated defensive tests. If not, play around with adjusting the prompt, but keep in mind sometimes it may be better to write it yourself.

Check for exceptions: If a method is expected to throw an exception under certain conditions, write a test to confirm that this happens. For example, you might have a test for the putPost method that checks if an exception is thrown when the method is called with an invalid post ID.

Challenge

If you finish early, review the other tests to see if there are additional improvements that can be made. Use Copilot to help explain the tests and/or to potentially add to them.