Automating Testing and Security with AI Coding Agents: A Practical Guide
AI coding agents can generate features quickly, but how do you know the code is safe to ship? Learn how to automate tests, dependency checks, code scanning, and security reviews with a practical AI-assisted CI workflow.
Automating Testing and Security with AI Coding Agents: A Practical Guide
AI coding agents can build a feature in minutes. They can create components, connect APIs, write database queries, and even generate tests.
But there is an important question you should ask before shipping the result:
How do you know the code actually works, and how do you know it is safe?
A feature can look correct while containing a broken edge case. A form can accept invalid input. An API can expose information to the wrong user. A dependency can introduce a known vulnerability. And a test suite generated by the same agent that wrote the feature may simply repeat the assumptions made during implementation.
This is why testing and security should not be optional final steps in vibe coding.
In this guide, we'll build a practical workflow that combines automated tests, code quality checks, dependency scanning, security analysis, and AI-assisted code review. We'll also show how to run these checks automatically when code is pushed or a pull request is opened.
The goal is not to make an AI agent responsible for guaranteeing security. The goal is to create a system where problems are easier to detect, changes are easier to review, and risky code is less likely to reach production.
1. Why AI-generated code needs independent verification
AI coding agents are useful because they can generate and modify code quickly. However, generated code still needs to be evaluated against the application's actual requirements.
Consider a simple expense-tracking feature.
You ask an agent to create a form that saves an expense. The interface looks correct, the submit button works, and the new record appears in the dashboard.
But have you checked whether:
- An amount of zero or a negative amount is accepted?
- A user can edit another user's expense by changing an ID?
- A failed database request produces a useful error?
- A repeated request creates duplicate records?
- The saved value is validated on the server?
- The application still builds after the change?
A screenshot cannot answer these questions. A successful build cannot answer all of them either.
Different verification methods find different kinds of problems.
| Verification method | What it helps detect |
|---|---|
| Unit tests | Incorrect behavior in individual functions |
| Integration tests | Problems between components, services, or database operations |
| End-to-end tests | Broken user journeys |
| Type checking | Invalid types and incompatible interfaces |
| Linting | Code-quality and consistency problems |
| Dependency scanning | Known vulnerabilities in third-party packages |
| Static security analysis | Potentially unsafe code patterns |
| Manual review | Context-specific risks and incorrect assumptions |
No single check replaces the others. A reliable workflow uses several layers according to the risk of the application.
2. Build a testing strategy before asking the agent to code
Do not start by asking an AI agent to generate hundreds of tests. First identify what must work.
For each feature, define its expected behavior and acceptance criteria.
For example, an expense creation feature might have these requirements:
Expected behavior
- An authenticated user can create an expense.
- The amount must be a valid positive number.
- The category must be valid.
- The expense belongs to the authenticated user.
- A successful save updates the transaction list.
- A failed save displays a useful error.
Important negative scenarios
- An unauthenticated request is rejected.
- Invalid amounts are rejected.
- A user cannot create a record for another user.
- Missing required fields are rejected.
- Database failures do not produce false success messages.
This becomes the basis for your tests.
Use the right testing level
Unit testing
Test small pieces of behavior independently. For example, test a function that calculates a monthly expense total.
Integration testing
Test whether connected parts work together. For example, verify that an API validates an expense, saves it, and returns the expected response.
End-to-end testing
Test the experience from the user's perspective. For example, sign in, add an expense, and confirm that it appears in the transaction list.
Start with the most important user journeys. Add more coverage as the application grows.
3. Let AI generate tests, but make the requirements independent
An AI coding agent can help write test cases, but the expected behavior should come from the product requirements—not simply from whatever implementation the agent produced.
A useful approach is to ask the agent to create a test plan before it writes tests.
Use this prompt:
Review the feature requirements and current implementation.
Do not modify the application code yet.
Create a test plan covering:
1. Expected successful behavior.
2. Invalid and missing input.
3. Boundary values and edge cases.
4. Authentication and authorization.
5. Database and API failures.
6. Duplicate requests where relevant.
7. Regression risks to existing behavior.
For each scenario, describe:
- The setup
- The action
- The expected result
- The appropriate testing level
Do not assume the current implementation is correct.
Derive expected results from the requirements.
Identify any missing or ambiguous requirements.
Review the plan. Correct missing scenarios and unclear expectations before asking the agent to implement the tests.
This makes it less likely that the agent will simply write tests that confirm its own assumptions.
4. Automate browser testing with Playwright
For web applications, browser automation helps verify what users actually experience.
Playwright is one option for end-to-end testing. It supports Chromium, Firefox, and WebKit, and provides tools for interacting with pages and checking visible behavior.
For a JavaScript or TypeScript project, install it using:
npm init playwright@latest
Follow the setup prompts and choose the configuration that matches your project.
Example: Test an expense creation journey
The following example assumes your application has a page with an expense form, accessible labels, and a visible success message. Adapt the selectors and expected text to your actual application.
import { test, expect } from '@playwright/test';
test('user can create an expense', async ({ page }) => {
await page.goto('/expenses/new');
await page.getByLabel('Description').fill('Internet bill');
await page.getByLabel('Amount').fill('1200');
await page.getByRole('button', {
name: 'Save expense',
}).click();
await expect(
page.getByText('Expense saved successfully')
).toBeVisible();
await expect(
page.getByText('Internet bill')
).toBeVisible();
});
This test checks a user journey rather than the internal implementation of a component.
You should also add negative scenarios, such as submitting an invalid amount and verifying that the application displays the expected validation message.
Make browser tests reliable
A few practices make a big difference:
- Prefer accessible locators such as roles and labels.
- Keep tests independent of one another.
- Use controlled test data.
- Avoid relying on arbitrary time delays.
- Verify user-visible results.
- Mock third-party services when you need predictable responses.
- Use a dedicated test or staging environment instead of production data.
Playwright recommends testing user-visible behavior, isolating tests, and using retryable assertions. Its documentation is a useful reference when building a maintainable suite.
Reference: Playwright Best Practices.
5. Add code quality checks to every change
Automated tests are important, but they do not catch every problem.
For a TypeScript project, you may also run:
npm run lint
npm run typecheck
npm test
npm run build
These are example script names. Check your project's package.json and use the actual scripts configured in your repository.
Each check has a different purpose:
- Linting: Finds suspicious patterns and style issues.
- Type checking: Finds type errors and incompatible usage.
- Tests: Verify expected behavior.
- Build: Checks whether the application can be compiled for deployment.
A passing build does not mean that the application is functionally correct or secure. Treat it as one verification layer.
6. Automate dependency security checks
Most modern applications depend on third-party packages. These packages save development time, but they also introduce supply-chain risk.
A package may contain a known vulnerability, become unmaintained, or pull in another vulnerable dependency.
For an npm-based project, start with:
npm audit
This checks the dependency tree against known vulnerability information available to the configured npm registry.
You can set a minimum severity threshold:
npm audit --audit-level=high
You can also ask npm to apply compatible fixes:
npm audit fix
However, do not run automatic dependency fixes blindly.
A fix can change package versions, introduce compatibility issues, or require a larger migration. Review the proposed changes, run your tests, and inspect the lockfile.
Avoid using --force as a default solution. It can allow changes outside your declared version ranges, including breaking major-version updates.
Reference: npm audit documentation.
Check dependencies when pull requests are opened
If you use GitHub, dependency review can help identify vulnerable packages introduced by a pull request.
This is useful because it checks proposed dependency changes before they become part of the main branch.
Reference: GitHub Dependency Review.
7. Add static security analysis
Static analysis examines source code for potentially dangerous patterns without needing to execute the application.
For repositories that support it, GitHub CodeQL can identify security-related problems in supported languages.
Code scanning can help find issues such as unsafe data handling and injection-related patterns, depending on the language, query coverage, and configuration.
Start with GitHub's setup guidance:
Do not assume every repository has access to every CodeQL feature. Availability depends on repository visibility, plan, and security configuration.
Understand what the scanner cannot prove
A clean static-analysis report does not prove that an application is secure.
For example, a scanner may not know whether a particular user should be allowed to view another user's record. That requires understanding your application's business rules and authorization model.
Use static analysis as an additional source of evidence, not as a replacement for security review.
8. Use OWASP as a security review checklist
When building web applications, it helps to have a consistent list of security risks to consider.
The OWASP Top 10:2025 is a useful awareness resource covering major web application security risk categories.
Some important areas to review include:
Broken access control
Can one user access another user's private records by changing an ID or API request?
Security misconfiguration
Are debug features, overly permissive settings, or unnecessary services exposed?
Software supply-chain failures
Are dependencies, build tools, and workflow actions trustworthy and maintained?
Cryptographic failures
Are sensitive values stored and transmitted using appropriate protections?
Injection
Can untrusted input change the meaning of a database query or command?
Authentication failures
Are sessions, login flows, password handling, and account recovery implemented safely?
Insecure design
Does the application lack security requirements or safeguards for important user journeys?
Software or data integrity failures
Can untrusted updates or build inputs alter what gets executed?
Security logging and alerting failures
Are important security events recorded appropriately without exposing secrets?
Mishandling exceptional conditions
Do failures expose sensitive details or leave the application in an unsafe state?
Use the OWASP list to guide review and threat modeling. It is not a complete penetration-testing procedure or a certification that your application is secure.
9. Create a CI workflow that runs checks automatically
Running tests manually is useful while developing. But people forget, commands get skipped, and changes can reach the main branch without being verified.
Continuous Integration (CI) automates checks when code is pushed or a pull request is opened.
For a GitHub repository, create:
.github/
└── workflows/
└── quality-checks.yml
Here is a starting workflow for a JavaScript or TypeScript application that uses npm:
name: Quality Checks
on:
push:
branches: [main]
pull_request:
branches: [main]
permissions:
contents: read
jobs:
quality:
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Set up Node.js
uses: actions/setup-node@v4
with:
node-version: 22
cache: npm
- name: Install dependencies
run: npm ci
- name: Run lint
run: npm run lint
- name: Run type checks
run: npm run typecheck
- name: Run tests
run: npm test
- name: Build application
run: npm run build
- name: Audit dependencies
run: npm audit --audit-level=high
This is a template, not a universal workflow. Before using it:
- Confirm the Node.js version supported by your application.
- Confirm the package manager and lockfile.
- Replace script names with commands that actually exist.
- Configure required environment variables using test-only values.
- Add database or service setup if integration tests need it.
- Review and update action versions according to your repository's security policy.
For stronger workflow security, pin third-party actions to verified full commit SHAs and review permission requirements. GitHub explains the risks of relying on movable tags in its workflow dependency lockfile documentation.
What happens when a check fails?
The workflow should report failure instead of allowing an unverified change to appear successful.
You can configure branch protection or repository rules so required checks must pass before a pull request can be merged.
This creates a practical release boundary:
Code change → Automated checks → Review → Approval → Merge
GitHub Actions can run workflows on pushes and pull requests. Playwright also documents how to execute browser tests in CI and publish reports.
Reference: Playwright CI.
10. Give your AI coding agent a security review workflow
AI agents can assist with reviewing changes, identifying suspicious patterns, generating tests, and explaining potential vulnerabilities.
But the agent should not be the only security control.
A useful workflow separates implementation from review.
- Ask one agent to implement the approved feature.
- Run automated tests and security tools.
- Ask for an independent review of the diff.
- Investigate the findings.
- Fix confirmed issues.
- Rerun the relevant checks.
- Have a human review high-impact changes.
Reusable security review prompt
Use this prompt after a meaningful feature implementation:
Act as an independent application security reviewer.
Review the current changes and relevant surrounding code.
Do not modify files during this review.
Focus on:
1. Authentication and authorization.
2. User-to-user data isolation.
3. Input validation and injection risks.
4. Secret and sensitive-data exposure.
5. Unsafe file uploads and downloads.
6. API error handling and information disclosure.
7. Dependency and configuration risks.
8. Logging of sensitive information.
9. Missing tests for security-critical behavior.
10. Changes that weaken existing security controls.
For each finding, provide:
- Severity and rationale.
- Affected file and relevant code location.
- A realistic attack or failure scenario.
- Evidence from the repository.
- A recommended remediation.
- A test that would help prevent regression.
Separate confirmed issues from concerns that need more
context or manual verification.
Do not claim that the application is secure simply
because no issue was found.
Do not change code during this review.
This prompt encourages the agent to provide evidence and explain impact instead of returning a generic list of security recommendations.
Ask for fixes only after reviewing findings
Once you have evaluated the report, use a separate implementation prompt:
Fix the confirmed security findings from the reviewed report.
Before editing:
- Inspect the affected code and existing conventions.
- Preserve the intended application behavior.
- Identify any breaking changes or migrations.
For each fix:
- Implement the smallest appropriate change.
- Add a regression test.
- Avoid weakening existing security controls.
- Do not introduce unnecessary dependencies.
After implementation:
- Run relevant tests and security checks.
- Inspect the final diff.
- Report the exact commands and results.
- Identify anything that still requires manual review.
Do not claim that an issue is resolved without verification.
Separating review and implementation makes it easier to challenge incorrect findings and prevents an agent from silently approving its own changes.
11. Build a practical release checklist
Before shipping an AI-generated feature, use a checklist that covers both behavior and security.
Functional verification
- The feature matches its acceptance criteria.
- Important user journeys work end to end.
- Invalid inputs are rejected.
- Empty, loading, success, and error states are handled.
- Existing features have not regressed.
Code quality
- Linting passes.
- Type checking passes where configured.
- Relevant unit and integration tests pass.
- The production build succeeds.
- The final diff contains only intended changes.
Security
- Server-side validation is in place.
- Authorization is enforced on protected operations.
- No real secrets are committed or exposed to the browser.
- Dependency vulnerabilities are reviewed.
- Static security findings are investigated.
- Sensitive data is not exposed in logs or error messages.
- Security-critical changes receive human review.
Release readiness
- CI checks have completed successfully.
- Required reviews and approvals are complete.
- Deployment configuration is correct.
- A recovery or rollback plan exists where appropriate.
- Monitoring is available for important production behavior.
A checklist does not guarantee a secure release. It makes important verification steps visible and repeatable.
12. Common mistakes when automating testing and security
Asking the agent to test only the happy path
A successful user journey is important, but it does not cover invalid input, unauthorized access, failed requests, or boundary conditions.
Ask for negative and edge-case scenarios too.
Letting the agent write and approve its own tests
Tests based entirely on the implementation can reproduce the same assumptions and mistakes.
Define expected behavior from independent requirements and review the test plan.
Treating a clean security scan as proof of security
Tools detect the patterns and risks they are designed to detect. Business-logic flaws, access-control mistakes, and missing requirements can remain.
Combine tools with manual review and testing.
Automatically fixing every dependency warning
Blindly applying updates can introduce breaking changes. Review the proposed changes, especially when major versions or production dependencies are involved.
Running tests against production data
Use isolated test data and controlled environments. Tests should not create, delete, or modify real customer records.
Giving agents unrestricted access to production
Use least privilege. Do not give an agent access to credentials, infrastructure, or destructive actions that are not needed for its task.
Ignoring failed checks
A failed check should be investigated. Do not remove a test, weaken a security rule, or bypass a CI requirement just to obtain a green status.
13. A practical implementation plan
You don't need to introduce every tool on the first day.
Start with a small sequence:
Stage 1 — Establish a baseline
Identify your current test commands, build process, dependency manager, and existing security controls.
Stage 2 — Cover the critical user journey
Add tests for the most important application workflow, including at least a few failure scenarios.
Stage 3 — Add automated code checks
Run linting, type checks, tests, and builds consistently.
Stage 4 — Add dependency and code scanning
Use the security tools supported by your language, package manager, and repository platform.
Stage 5 — Connect checks to CI
Run the checks on pull requests and pushes to the branches that matter.
Stage 6 — Introduce independent AI-assisted reviews
Use a separate review step to examine meaningful changes and security-sensitive areas.
Stage 7 — Establish release requirements
Define which checks must pass and which changes require human approval.
Expand the system based on actual failures, risk, and project complexity. A small application does not need the same pipeline as a system handling payments or sensitive customer data.
Frequently asked questions
Can AI coding agents write automated tests?
Yes. They can generate unit, integration, and browser tests. However, you should define expected behavior independently and review whether the tests cover meaningful failure scenarios.
Is Playwright enough to test an application?
No. Playwright is useful for browser-based end-to-end testing, but it does not replace unit tests, integration tests, server-side security checks, dependency scanning, or manual review.
Does npm audit guarantee that dependencies are safe?
No. It reports known vulnerabilities based on the available advisory information. It does not prove that a package has no unknown vulnerabilities or malicious behavior.
Should security scanning run on every commit?
For many projects, running appropriate checks on pull requests and important branch updates is a useful baseline. The exact frequency depends on the application's risk, repository size, and available CI resources.
Can an AI agent perform a complete security audit?
An agent can assist with code review and explain potential issues, but it cannot guarantee a complete audit. High-risk applications may need specialist security reviews, threat modeling, and penetration testing.
What should happen when a CI security check fails?
Investigate the finding, determine whether it is real and relevant, and fix or document it through an approved process. Do not bypass the check simply to merge the code.
Final thoughts
AI coding agents can accelerate development, but speed is not the same as reliability.
A working feature is only the beginning. You need to verify its behavior, inspect its dependencies, check how it handles untrusted input, and make sure important operations are protected.
Start with a few meaningful tests. Add code-quality and dependency checks. Run them automatically through CI. Use AI agents to help investigate and review changes, but keep independent verification and human approval for high-impact decisions.
The goal isn't to create a pipeline that never fails. It's to create one that catches problems early, explains what went wrong, and makes it harder for unverified changes to reach users.
Generate faster. Test independently. Review carefully. Ship responsibly.
Continue the Series
If you're building applications with AI coding agents, continue with these practical guides:
- The Ultimate Pre-Vibe-Coding Checklist: Prepare your project before writing the first prompt. Read here
- AI Agent Rules for Vibe Coding: Use
AGENTS.mdand supporting Markdown files to give coding agents reliable project context. Read here - The UI/UX Checklist for Vibe-Coded Applications: Improve usability, accessibility, responsive layouts, and real-world interactions before shipping. Read here
- The Complete Vibe Coding Starter Kit: Bring project rules, reusable prompts, and development workflows together. Read here
- Vibe Coding Third-Party Integrations Safely. Learn how to connect APIs, webhooks, and external services without creating avoidable reliability and security problems. Read here
Was this post helpful?
Comments
Be the first to commentBe the first to share your thoughts.