The Ultimate Library of ChatGPT Prompts for Writing Unit Tests
Stop wasting hours writing boilerplate unit tests. With the right ChatGPT prompts, you can automate test generation, cover edge cases you might have missed, and focus on building features. This curated prompt pack helps you leverage AI for a more efficient Test-Driven Development (TDD) workflow, ensuring your code is robust and reliable from the start. Use ChatBoost to access these prompts instantly with a keyboard shortcut (Alt+P).
Create a basic Jest unit test for a simple JavaScript/TypeScript function, covering the happy path.
Act as a senior software engineer specializing in Test-Driven Development. Write a Jest unit test for the following TypeScript function. The test should follow the Arrange-Act-Assert pattern and verify the correct output for a typical input.
typescript...
Generate Pytest for Class Method
Quickly generate a Pytest test case for a method within a Python class.
As a Python testing expert, write a Pytest unit test for the `add_item` method in the following `ShoppingCart` class. Ensure the test initializes the class, calls the method, and asserts that the item was added correctly.
python...
Generate JUnit Happy Path Test
Create a standard JUnit test for the primary success scenario of a Java method.
Act as a Java QA engineer. Write a JUnit 5 test for the happy path of the `calculateBonus` method below. Use appropriate assertions from `org.junit.jupiter.api.Assertions`.
java...
Identify Potential Edge Cases
Brainstorm a list of edge cases and boundary conditions to test for a given function.
Analyze the following function and list all potential edge cases, boundary conditions, and invalid inputs that should be tested. Categorize them by type (e.g., Null Inputs, Empty Strings, Zero Values, Max/Min Values).
javascript...
Test Error Throwing with Jest
Write a Jest test to confirm that a function correctly throws an error under specific conditions.
Write a Jest unit test for the function below to verify that it throws a `TypeError` when the `email` parameter is not a valid email format. Use `toThrow()` or a similar Jest matcher.
javascript...
Test Invalid Inputs with Pytest
Generate a Pytest test to handle invalid data types or values passed to a Python function.
Write a Pytest test using `pytest.raises` to ensure the `calculate_average` function below correctly raises a `ValueError` when given an empty list.
python...
Mock API Call with Jest
Create a Jest test that mocks an API call (e.g., using Axios) to avoid actual network requests.
I need to test the `fetchUserData` function below. Write a Jest test that mocks the `axios.get` call. The mock should return a fake user object, and the test should assert that the function processes and returns the user's full name.
javascript...
Mock Dependency with Mockito
Generate a Java JUnit test using Mockito to mock a service dependency.
Act as a Java TDD expert. Write a JUnit 5 test for the `OrderService` class below. Use Mockito to mock the `PaymentGateway` dependency. The test should verify that the `processOrder` method returns `true` when `paymentGateway.charge()` returns `true`.
java...
Write First TDD Failing Test
Start a TDD cycle by generating the initial failing test based on a feature requirement.
I am practicing Test-Driven Development. My requirement is to create a function `isPasswordStrong(password: string)` that returns `true` if a password is at least 8 characters long and contains at least one number. Write the first simple failing unit test for this requirement using Jest. The test should check the minimum length requirement.
Generate Test Cases from User Story
Convert a user story or feature specification into a list of descriptive unit test cases.
Read the following user story and generate a comprehensive list of unit test case descriptions (not the code). The list should cover happy paths, edge cases, and error conditions.
**User Story:**...
Refactor Test for Readability
Improve an existing unit test by applying the Arrange-Act-Assert pattern for better clarity.
Refactor the following unit test to improve its readability and structure. Clearly separate the 'Arrange', 'Act', and 'Assert' sections with comments.
javascript...
Suggest Tests for Better Coverage
Analyze a function and suggest new unit tests to cover logical branches that are currently untested.
Analyze the following function. Identify which logical branches or conditions are not covered by the existing test. Then, describe the new unit tests needed to achieve higher test coverage.
**Function:**...
Generate Go Table-Driven Test
Create a table-driven test in Go for a utility function to test multiple scenarios concisely.
Act as a Golang expert. Write a table-driven unit test for the following `Sum` function in Go. Include test cases for positive numbers, negative numbers, and an empty slice.
go...
Generate RSpec Model Validation Test
Create an RSpec test to verify validations on a Ruby on Rails model.
Write an RSpec test for the following Rails `User` model. The test should verify the presence and uniqueness validations for the `email` attribute.
ruby...
Generate Boundary Value Tests
Create test cases using boundary value analysis for a function that accepts a numerical range.
I have a function `isWithinRange(value, min, max)` that checks if `value` is between `min` and `max` (inclusive). Using boundary value analysis, generate a set of Jest test cases for a range of 10 to 20. Include tests for values just inside, at, and just outside the boundaries (e.g., 9, 10, 11, 19, 20, 21).
Mock Database with Pytest
Write a Pytest test using `unittest.mock` to patch a database connection or ORM call.
I need to test the `get_user_from_db` function without hitting the actual database. Write a Pytest test that uses `unittest.mock.patch` to mock the `db.session.query` call and returns a mock user object.
python...
Mock Repository with Moq (C#)
Write a C# unit test using the Moq framework to mock a repository interface.
Act as a .NET developer. Write an NUnit test for the `UserController`'s `Get` method below. Use the Moq framework to mock the `IUserRepository` dependency. The mock should be set up to return a user object when `GetUserById` is called with a specific ID.
csharp...
Write Test for a New Feature
Following TDD, write a unit test for a new feature before its implementation exists.
I'm adding a new feature to my `ShoppingCart` class: a method called `applyDiscount(percentage)`. This method should reduce the total price by the given percentage. Write a new, failing Pytest unit test that verifies this functionality. Assume the cart has items totaling 100.0 and apply a 10% discount.
Convert to Parameterized Test
Refactor multiple, similar unit tests into a single, cleaner parameterized test.
Refactor these three separate Jest tests into a single, parameterized test using `test.each`. This will make the test suite more concise and maintainable.
javascript...
Explain a Failing Test Output
Paste a failing test's console output and ask for a likely explanation of the cause.
I'm debugging a failing unit test. Based on the function code and the test output below, what is the most likely cause of the failure? Explain your reasoning.
**Function Code:**...
Generate NUnit Test for Controller
Create an NUnit test for a C# ASP.NET controller action, checking the result type.
Write a basic NUnit test for the `Index` action of the following ASP.NET Core MVC `HomeController`. The test should verify that the action returns a `ViewResult`.
csharp...
Mock an Entire Module in Jest
Generate a Jest test that mocks a complete module, such as the Node.js 'fs' module.
I have a function that reads a file using Node's `fs` module. Write a Jest test for the `readConfigFile` function below, but mock the entire `fs` module. Specifically, mock `fs.readFileSync` to return a fake JSON string `{"mode":"test"}`.
javascript...
Stub a Method with RSpec
Write an RSpec test that stubs a method on a collaborator object to control its output during a test.
Write an RSpec test for the `Notifier` class. The test should check the `send_welcome_email` method. Use RSpec's stubbing capabilities to create a `user` double and stub its `email` method to return 'test@example.com'.
ruby...
Test Nil Inputs in Go
Write a Go test to ensure a function handles nil inputs gracefully without panicking.
Write a Go unit test for the function below. The test should verify that the function does not panic and returns an empty string when a `nil` user pointer is passed as an argument.
go...
Test Exception Message with JUnit
Generate a JUnit test to check for a specific exception type and verify its message.
Write a JUnit 5 test for the `setAge` method below. The test must verify that an `IllegalArgumentException` is thrown and that the exception's message is exactly "Age must be non-negative".
java...
Test Async Function with Pytest
Generate a test for an asynchronous Python function using `pytest-asyncio`.
I have an `async` function in Python that fetches data. Write a test for it using `pytest-asyncio`. The test should mock the `aiohttp` client session to return a mock response without making a real network request.
python...
Test React Component Rendering
Create a basic test using React Testing Library and Jest to ensure a component renders correctly.
Write a simple test for the React component below using React Testing Library and Jest. The test should render the `Greeting` component with a `name` prop and assert that the correct greeting text is present in the document.
jsx...
Turn these prompts into a reusable workspace
Save your favourite prompts once, reuse them with Alt+P, keep a live Table of Contents of long chats, and export conversations when you're done.