Use Cursor's Composer feature to have AI generate test code from scratch.

Hello, I'm Masa, a backend engineer at AGEST.

In this article, I'll introduce how to use the Composer feature in the Cursor editor to generate test code with AI. Writing test code is essential for improving software quality, but doing it manually can be time-consuming. By leveraging AI, we can generate test code more efficiently.

I'll explain the process step by step with concrete examples.

Note: The Cursor Composer feature currently requires the Pro version. However, the Free version includes a two-week Pro trial, so keep that in mind.

[Reference] Cursor Pricing

What is the Cursor Editor?

Cursor is a new AI-powered code editor forked from VSCode. If you're a VSCode user, you'll find its interface and usability familiar, making the transition seamless. It offers various productivity-enhancing features like code completion and refactoring support. With the Composer feature, you can analyze entire codebases and generate code automatically.

Setting Up the Environment

Installing Cursor

First, download and install Cursor from the official website.

[Cursor Official Website]

After installation, launch Cursor.

Once opened, navigate to User Settings > Cursor Settings to configure your preferences.

In the settings menu, navigate to "Features" and enable Composer.

Preparing the Project

Prepare the code that will be tested. Here, we’ll use an example written in Go, but the same steps can be followed for other languages.

example/ ├── main.go └── utils/     ├── example.go     └── item.go

Creating the Code to Be Tested

First, implement the structure to be tested in utils/item.go.

package utils

// Item構造体を定義します
type Item struct {
	ID    int    // アイテムのID
	Name  string // アイテムの名前
	Price int    // アイテムの価格
}

Implementing the Function to Be Tested

Next, implement the function to be tested in utils/example.go.

// utilsパッケージに含まれるユーティリティ関数を定義します
package utils

// ItemsTotalPriceは、与えられたItemスライスの合計価格を計算します
func ItemsTotalPrice(items[]Item) int {
  total:= 0 // 合計価格を初期化

  // 各アイテムの価格を合計に加算
  for _, item := range items {
    total += item.Price
  }

  return total // 合計価格を返却
}

Generating Test Code Using the Composer Feature

Steps to Generate Test Code:

1. Open the example.go file in Cursor.

2. Press Ctrl + I to bring up the Composer input screen in Cursor.

3. Click the "+" button in the input file section and add item.go.

4. Enter the prompt: "Create test code for ItemsTotalPrice."

5. Composer will use AI to generate the test code.

Reviewing the Generated Test Code

The automatically generated test code is as follows.

/**
 * TestItemsTotalPrice tests the ItemsTotalPrice function.
 *
 * This test verifies the following cases:
 * 1. When the slice is empty
 * 2. When the slice contains a single item
 * 3. When the slice contains multiple items
 *
 * @param t *testing.T Test object used to run the test
 */
// Define test cases
testCases:= []struct {
    name     string
  items[]Item
    expected int
} {
  {
    name: "Empty slice",
      items: []Item{ },
    expected: 0,
    },
  {
    name: "Single item",
      items: []Item{
      { ID: 1, Name: "Item 1", Price: 100 },
    },
    expected: 100,
    },
  {
    name: "Multiple items",
      items: []Item{
      { ID: 1, Name: "Item 1", Price: 100 },
      { ID: 2, Name: "Item 2", Price: 200 },
      { ID: 3, Name: "Item 3", Price: 300 },
    },
    expected: 600,
    },
}
// Execute each test case
for _, tc := range testCases {
  t.Run(tc.name, func(t * testing.T) {
    // Call the ItemsTotalPrice function
    result:= ItemsTotalPrice(tc.items)

        // Compare the expected and actual results
        if result != tc.expected {
    t.Errorf("Expected: %d, Actual: %d", tc.expected, result)
  }
    })

Explanation of the Test Code

  • When the item list is empty: Verifies that the total is 0 when an empty slice is passed.
  • When there is one item: Checks whether the total price is correctly calculated for a single item.
  • When there are multiple items: Ensures that the total price is correctly calculated in a normal case with multiple items.

In each case, the expected total price is compared with the actual result, and an error message is displayed if there is a mismatch.

Committing the Code

If the test results show no issues, click "Accept all" to confirm the generated test code.

Returning to the Editor

Press Ctrl + i again to return to the editor screen. You should see that utils_test.go has been created under the utils directory.

Running the Test Code

Execute the following command in the terminal to run the test and verify the results:

go test./...

Test Success Confirmation

If all tests pass, it means the implementation is successful.

Advantages of the Composer Feature

Multiple Input Files

One of the biggest advantages of Composer is its ability to specify multiple input files.

While GitHub Copilot can achieve similar results, generating truly practical and useful code requires referencing multiple sources within the project rather than relying on a single file.

Cursor’s Composer allows users to specify multiple input files, ensuring that all necessary information is provided.

File Generation

Traditional AI code generators can output code to the screen but cannot directly create files.

With Cursor, the proposed content is output directly as a file, streamlining the development process.

Suggested File Modifications

When code modifications are needed, Cursor does not overwrite the existing code immediately.

Instead, it presents suggested changes, allowing users to review and approve them via keyboard input.

This makes it easier to verify and apply modifications selectively.

Conclusion

By utilizing Cursor’s Composer feature, the process of writing test code becomes significantly more efficient. The ability to input multiple files allows for the generation of much more practical and usable code than before.

While this guide focused on test code generation, Composer can also be used to generate main source code. By inputting specifications as a prompt, you can have Composer generate the necessary code, assemble the main logic, and even modify existing implementations. Of course, as with any AI tool, reviewing the final output with your own eyes remains essential.

Moving forward, we aim to continue leveraging AI tools to balance development efficiency and code quality.

This article was originally published in Japanese on Sqripts and has been translated with minor edits for clarity.

Turn your vision into a tangible reality

We've been doing this for 30 years - helping businesses like yours with software development and testing. Let's connect and explore how we can support your goals.

Related Posts