Use ChatGPT for Test-First Development

Test-first development (TDD) is a development methodology in which programmers write unit tests before writing the software itself. The tests serve both as a check that the software is correct, and as a specification that describes what each function in the program should do.

Can you do TDD with ChatGPT? Yes—and no—and yes again. TDD has an inherent “chicken and egg” problem: while you don’t start by writing any functions or classes for the system you’re building, you do have to think fairly precisely about the API you’re designing. By itself, forcing programmers to think carefully about the API up front is a significant benefit. In the context of ChatGPT, thinking about the API up front is essential if you want it to generate good code, or code that will become part of a larger project. And that’s part of the difference between being a hobbyist programmer and a professional.

So what happens when you ask ChatGPT to generate tests first? Here’s a prompt that asks ChatGPT to write tests for a function that solves a simple geometry problem:

Prompt: Write a unit test for a function that computes the volume between two spheres. That function will have three arguments: the radius of one sphere, the radius of the second, and the distance between their centers. All arguments will be floating point. The smaller sphere must lie within the larger sphere. The case where the two spheres ...

Get Use ChatGPT for Test-First Development now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.