Reviewing and testing AI-written code
Why it matters
- An AI agent can produce a large volume of Kotlin code in seconds. Without a structured review, a Context leak in a ViewModel or a hardcoded API key can ship to production before anyone reads the diff.
- Interviewers at senior-level Android roles ask how you gate AI-generated code: what pipeline you run, what hooks you configure, and how you handle a case where tests pass but users crash.
- Guardrails such as CLAUDE.md, hooks and deny rules in
.claude/settings.json, and skills in.claude/skills/reduce context errors, but they do not eliminate logic bugs. A human must still read the diff. - A missing ProGuard keep rule or an uncollected Flow will not fail unit tests. Only a release build or an instrumented test catches it, and the agent may skip that step.
The simple explanation
- You hire a fast junior developer who writes code quickly but has never seen your codebase.
- You do not trust the output; you read every line.
- You run the full test suite before merging.
- You check that they did not touch the signing key or the production database password.
- You add a checklist so the next sprint is faster, not looser.
An AI agent (Claude Code in your terminal, Gemini Agent Mode in Android Studio) reads your repo, generates a diff, and may run ./gradlew test or ktlintCheck before handing back. The output is a set of file edits. Your job is the same as reviewing a junior developer's PR, except the junior can produce a large diff in seconds and may hallucinate APIs that do not exist on the type.
A practical review has three layers:
| Layer | What you check | Tool |
|---|---|---|
| Static | Lint, ktlint, detekt, no secrets in diff | ./gradlew ktlintCheck, gitleaks |
| Behavioural | Unit tests, instrumented tests, release build | ./gradlew testDebugUnitTest, connectedDebugAndroidTest, assembleRelease |
| Semantic | Logic correctness, missing edge cases, API misuse | Human reading the diff |
The semantic layer is where AI code fails most. The code compiles, tests pass, but the logic is wrong: a ViewModel holds a Context, a StateFlow is never collected in a lifecycleScope, a Room query returns a List instead of a Flow<List>. The agent's own test run may use a fake that does not model the real failure path.
Guardrails reduce risk. A CLAUDE.md at the repo root tells the agent your conventions. Hooks in .claude/settings.json can run ktlint on PostToolUse or block edits to *.jks files on PreToolUse (exit code 2 blocks the call), and permission deny rules can keep the agent away from secret files. Skills in .claude/skills/ load project-specific instructions on demand. MCP servers give the agent access to CI logs or design tokens. But none of these replace a human reading the diff. Treat every AI-generated change like a junior colleague's pull request: read it, test it, and sign off on it.
Notes
- Treat every AI-generated diff like a junior PR: read every changed line, not just the agent's summary of what it did.
- Run the full verification pipeline after every agent edit: ktlint, unit tests, instrumented tests, and
./gradlew assembleReleaseto catch R8 or ProGuard issues. - Check for Context leaks: a
ViewModelorRepositorythat stores anActivityorContextreference is a memory leak that unit tests often miss. - Scan the diff for hardcoded secrets: API keys, tokens, keystore passwords. A secret in
BuildConfigor a Kotlin file is a security incident, not a style issue. - Verify API existence: AI may call a method that does not exist on the type. If the code compiles, the method exists; if it does not compile, the agent hallucinated the call.
- Check Flow and coroutine usage: collecting outside the lifecycle (no
repeatOnLifecycleorcollectAsStateWithLifecycle), work inGlobalScope, or an unbounded retry loop will often pass unit tests but waste battery, leak work, or show stale UI in production. - Configure
PreToolUsehooks ordenyrules in.claude/settings.jsonto block edits to*.jksandlocal.properties. The agent should never touch signing files. CLAUDE.mdand skills reduce context errors but do not eliminate logic bugs. A human must still read the diff and verify the intent.- Write a test for every new public function the agent adds. If the agent cannot write the test, you cannot verify the code, and you should not merge it.
- Never let an AI agent write or modify keystore files,
local.properties, orBuildConfigfields that hold secrets. Secrets stay on the server.
Code example
This bash script is a post-merge verification pipeline you run after an AI agent edits your Android project. It blocks dangerous file changes, runs lint and tests, builds the release variant, and scans for secrets.
#!/usr/bin/env bash
# post-ai-review.sh — run after an AI agent edits files
set -euo pipefail
# 1. Block changes to signing and secret files
if git diff --name-only HEAD~1 | grep -qE '(keystore|\.jks|\.p12|local\.properties|secrets)'; then
echo "BLOCKED: AI agent touched a signing or secret file."
exit 1
fi
# 2. Lint and style
./gradlew ktlintCheck --quiet
# 3. Unit and instrumented tests
./gradlew testDebugUnitTest --quiet
./gradlew connectedDebugAndroidTest --quiet
# 4. Release build catches R8 / ProGuard issues
./gradlew assembleRelease --quiet
# 5. Scan the diff for accidental secrets
if git diff HEAD~1 | grep -qE '(api[_-]?key|secret|token)\s*=\s*["'"'"'][A-Za-z0-9]{16,}'; then
echo "BLOCKED: possible secret in diff."
exit 1
fi
echo "All checks passed. Safe to merge."- Step 1 uses
git diff --name-onlyto catch any change to signing or secret files before anything else runs; this is the same check aPreToolUsehook performs, but here it is a post-merge safety net. - Step 4 runs
assembleRelease, notassembleDebug, because R8 and ProGuard strip code that unit tests never exercise. A missing keep rule only surfaces here. - Step 5 is a lightweight secret scan. In production, replace it with
gitleaksor a CI secret-scanning service for higher accuracy.
Run the idea in plain Kotlin
enum class Severity { BLOCKER, WARNING, INFO }
data class ReviewItem(
val name: String,
val severity: Severity,
val passed: Boolean
)
fun main() {
val items = listOf(
ReviewItem("No Context leak in ViewModel", Severity.BLOCKER, true),
ReviewItem("Network call has error handling", Severity.BLOCKER, false),
ReviewItem("ktlint passes", Severity.WARNING, true),
ReviewItem("Unit tests added for new code", Severity.WARNING, false),
ReviewItem("No hardcoded secrets in diff", Severity.BLOCKER, true),
ReviewItem("ProGuard rules updated", Severity.INFO, true)
)
val failedBlockers = items.filter { it.severity == Severity.BLOCKER && !it.passed }
val failedWarnings = items.filter { it.severity == Severity.WARNING && !it.passed }
println("Review summary for AI-generated diff:")
println("Blockers failed: " + failedBlockers.size)
for (item in failedBlockers) {
println(" [BLOCKER] " + item.name)
}
println("Warnings failed: " + failedWarnings.size)
for (item in failedWarnings) {
println(" [WARNING] " + item.name)
}
if (failedBlockers.isNotEmpty()) {
println("Decision: REJECT - fix blockers before merge.")
} else if (failedWarnings.isNotEmpty()) {
println("Decision: MERGE WITH NOTES - address warnings in follow-up.")
} else {
println("Decision: APPROVE.")
}
}In production
- An AI agent generated a ViewModel that stored an Activity Context to show a Toast.
- Users on low-RAM devices hit
OutOfMemoryErrorcrashes after rotating the screen many times; old Activities could not be garbage-collected. - Unit tests passed because the test used a fake Context that never triggered a rotation.
- The team wrote a custom Detekt rule that flags any Context or Activity reference inside a ViewModel class.
- A CLAUDE.md rule was added: no Context or Activity in ViewModels; UI messages go through UI state.
- LeakCanary was added to debug builds so a leaked Activity shows up during manual testing.
- An AI agent added a network client with a hardcoded API key in a Kotlin constant.
- The key shipped in the release APK and was extracted by a competitor.
- The agent's own test run passed because the test used a mock, not the real key.
- The team added a gitleaks scan to the CI pipeline that blocks any PR containing a secret pattern.
- The key was rotated and moved to a server-side endpoint; the client now calls a server that holds the secret.
- A CLAUDE.md rule was added: never write API keys, tokens, or passwords in app code or BuildConfig.
Common mistakes
- Trusting a green build. Code compiles and tests pass, but the logic is wrong. A ViewModel may hold a Context, a Flow may not be collected. Always read the diff and check the semantic layer.
- Reviewing only the agent's summary. The agent summarises its changes in a few sentences. The summary hides subtle bugs like a missing null check or a wrong generic type. Read every line of the diff.
- No test for new public code. The agent adds a public function but no test. You cannot verify correctness, and the next agent run may break it silently. Require a test for every new public function.
- Not reviewing build file changes. The agent modifies proguard-rules.pro or build.gradle and introduces a missing keep rule or a wrong dependency. The release build breaks or crashes at runtime. Flag these files for extra review, and run
assembleReleasein CI. - Ignoring deprecation warnings. The agent uses a deprecated API that still compiles. It may be removed in a later release. Run
./gradlew lintand treat deprecation warnings as errors in CI. - No secret scan in the pipeline. Secrets slip through because no tool checks for them. Add gitleaks or a CI secret-scanning step so a hardcoded key is caught before merge, not after release.
Interview questions
Answer out loud first. Then reveal the answer and compare it at each depth.
“How do you review AI-generated code differently from a human-written PR?”
“What verification pipeline do you run after an AI agent edits your Android project?”
“An AI agent's code passes all tests but users report a crash. What do you do?”
“How do you set up guardrails so an AI agent cannot break your release build?”
Quiz
What is the first thing to check when reviewing an AI-generated diff?
Which Gradle task catches ProGuard or R8 issues that unit tests miss?
What is the main semantic risk of AI-written Android code?
What does a PreToolUse hook in settings.json do?
0 of 4 answered
Mini task
15-minute exercise: review an AI-generated ViewModel
- Open your Android project in the terminal. Start Claude Code or Gemini Agent Mode.
- Ask the agent: "Add a UserProfileViewModel with a StateFlow that exposes a user profile fetched from a repository. Include error handling."
- Let the agent write the code and run its own tests. Note whether it actually ran
./gradlew testDebugUnitTestor skipped that step. - Run
./gradlew ktlintCheckand fix any style issues the agent missed. - Read the full diff. Check three things: (a) does the ViewModel hold a Context or Activity reference? (b) is the StateFlow collected with lifecycle awareness (
collectAsStateWithLifecyclein Compose, orrepeatOnLifecyclein Views)? (c) is there a try-catch or aResulttype around the network call? - Write a unit test for the new ViewModel using
runTestand a fake repository. Cover the success path and the error path. - Run
./gradlew testDebugUnitTestand./gradlew assembleRelease. - Scan the diff for any hardcoded string that looks like a secret (API key, token, password).
Done when: the diff passes ktlint, your new test passes, the release build succeeds, and you have written down three specific changes you would make if you were the reviewer (for example, switch to collectAsStateWithLifecycle, remove a Context reference and expose a UI event instead, or add a Result wrapper around the network call).