How to Write Test Cases for Camera Integration (With Examples)

How to Write Test Cases for Camera Integration (With Examples)

February 27, 2026 · 19 min read · How-To Guides

How to Write Test Cases for Camera Integration (With Examples)

Testing camera integration is a critical part of mobile and web application quality assurance because the camera touches hardware, OS permissions, UI rendering, and often business logic such as barcode scanning, AR overlays, or media capture. A well‑designed test suite catches crashes, permission mishandles, orientation glitches, and performance regressions before they reach users. This guide walks you through the full lifecycle of creating high‑signal test cases: from requirement breakdown to a concrete test matrix, from manual execution to automated scripts, and finally to how autonomous exploration can extend coverage. Every section contains actionable advice, real‑world examples, and snippets you can copy into your own test repository.

How to Write Test Cases for Camera Integration (With Examples): Defining Scope and Objectives

Before writing any test case, clarify what “camera integration” means for your product. Are you capturing still images, recording video, scanning QR codes, applying filters, or streaming AR content? Identify the entry points (e.g., a floating action button that opens the camera, a menu item “Scan”, or a web‑based that triggers the device picker). List the functional requirements, non‑functional requirements (latency, battery impact, storage usage), and regulatory constraints (e.g., GDPR for facial data). Write each requirement as a short, testable statement. For example:

Trace each requirement to a unique ID; this ID will later appear in your test case table, ensuring traceability. Once the scope is frozen, decide on the test levels you need: unit (mocking the camera API), integration (real device or emulator), and system (end‑to‑end user flow). For most camera features, integration and system tests provide the highest return on investment because they exercise the hardware‑software boundary.

How to Write Test Cases for Camera Integration (With Examples): Anatomy of a Robust Test Case

A test case that survives multiple releases shares a common structure. Use this template for every camera‑related case:

FieldDescriptionExample
IDUnique identifier, often prefixed with the requirement IDTC‑CAM‑001
TitleOne‑sentence summary of what is being verifiedVerify camera opens after permission grant
PreconditionsDevice state, app state, and any setup needed before step 1Device API ≥ 21, app installed, no existing camera permission
Test DataValues that drive the test (e.g., resolution, file size)Requested picture size: 1920×1080
StepsNumbered actions performed by tester or automation script1. Launch app → 2. Tap “Capture Photo” button → 3. System permission dialog appears → 4. Tap “Allow”
Expected ResultObservable outcome after the final stepCamera preview starts, UI shows shutter button, no crash
Post‑conditionsState that should hold after test (useful for chaining)Camera preview active, permission granted
PriorityP0 (blocker), P1 (high), P2 (medium), P3 (low) based on riskP0
TypeFunctional, negative, performance, security, accessibility, etc.Functional
Automation FeasibilityYes/No/Partial with notesYes – Appium can be clicked by UiAutomator2

Keep each field concise but complete. When you move to test management tools (e.g., Zephyr, Xray, or a simple spreadsheet), these columns become filterable attributes that let you generate dashboards, traceability matrices, and execution reports.

How to Write Test Cases for Camera Integration (With Examples): Positive Test Cases – Core Functionality

Positive test cases verify that the happy path works as specified. Below is a representative set; you will expand it based on your feature list. Each case assumes a clean device state (no lingering permissions, camera not in use by another app).

IDTitlePreconditionsStepsExpected Result
TC‑CAM‑001Camera opens after permission grantNo camera permission, app at home screen1. Tap “Capture Photo” button 2. System permission dialog appears 3. Tap “Allow”Camera preview starts within 2 seconds, UI shows shutter button
TC‑CAM‑002Photo capture saves JPEG with correct dimensionsCamera preview active, storage permission granted1. Tap shutter button 2. Confirm capture dialog (if any) 3. Return to gallery viewImage file appears in app‑private folder, dimensions 1920×1080, format JPEG, EXIF orientation correct
TC‑CAM‑003Video recording stops after max durationCamera preview active, video mode selected, storage permission granted1. Tap record button 2. Wait for 30 seconds (configured max) 3. Auto‑stop occursVideo file saved, duration 30 ± 0.5 s, codec H.264, audio track present
TC‑CAM‑004Switch between front and rear cameraCamera preview active (rear)1. Tap camera switch icon 2. Verify preview updatesPreview now shows front‑facing feed, no frame drop > 1 frame
TC‑CAM‑005Flash torch toggles on/off in previewCamera preview active, flash mode set to auto1. Tap flash icon until torch ON indicator appears 2. Tap again to turn OFFTorch indicator reflects state, preview brightness changes accordingly
TC‑CAM‑006Zoom pinch‑to‑zoom works smoothlyCamera preview active, zoom supported1. Place two fingers on preview 2. Spread apart to 2× zoom 3. Pinch back to 1×Preview scales without tearing, focus remains stable, UI zoom indicator updates
TC‑CAM‑007Exposure slider adjusts brightnessCamera preview active, exposure control available1. Slide exposure bar to +2 EV 2. Capture a photo 3. Slide to –2 EV and capture second photoFirst image noticeably brighter, second darker, histogram shift measurable
TC‑CAM‑008QR code scanning succeedsCamera preview active, scanner mode enabled1. Point camera at a valid QR code encoding “https://example.com” 2. Hold steady for ≤ 1.5 sApp decodes URL, navigates to the web page, no false positives
TC‑CAM‑009Barcode (EAN‑13) scanning worksCamera preview active, barcode scanner enabled1. Align barcode within guide lines 2. Tap scan buttonApp returns correct 13‑digit numeric code, no timeout
TC‑CAM‑010AR overlay renders on previewCamera preview active, AR session initialized1. Point camera at a known planar target 2. Wait for AR anchor acquisition3D model appears anchored to target, maintains pose under mild device motion
TC‑CAM‑011Capture in low‑light with night modeCamera preview active, night mode toggle ON1. Frame a dimly lit scene (< 5 lux) 2. Tap shutter 3. Wait for processingSaved image shows reduced noise, detail preserved, file size within expected range
TC‑CAM‑012Video recording with external microphoneCamera preview active, video mode, external mic connected via USB‑C1. Start recording 2. Speak into external mic 3. Stop recordingAudio track contains clear voice, no clipping, synchronization offset < 20 ms
TC‑CAM‑013PauseInterrupt and resume video recordingCamera preview active, video mode1. Start recording 2. Press home button to background app 3. Wait 5 s 4. Restore app from recentsRecording pauses, resumes seamlessly, final file duration equals sum of segments
TC‑CAM‑015Capture while device chargingDevice plugged into charger, battery at 20 %1. Open camera 2. Take photoCamera does not drop during capture image
TC‑CAM‑016Capture after rapid orientation changesCamera preview active1. Rotate device 90° left, wait for UI to settle 2. Rotate 90° right, wait 3. Repeat 5 times 4. Take a photoPreview remains upright, image saved with correct EXIF orientation, no UI glitch
TC‑CAM‑017Concurrent camera use with another app (share sheet)Another app holding camera (e.g., video call)1. From that app, invoke share → “Send image” → chooses camera 2. System shows “Camera in use” toast 3. Cancel shareApp handles gracefully, does not crash, user can retry after releasing camera
TC‑CAM‑018Permission rationale shown on denialCamera permission denied previously1. Re‑open camera flow 2. System shows rationale dialog (if implemented) 3. Tap “Learn more”Custom explanation screen appears, user can navigate to settings
TC‑CAM‑019Storage full handlingDevice storage < 10 MB free1. Attempt to capture photo 2. System throws storage full errorApp displays user‑friendly message, offers to free space or change storage location
TC‑CAM‑020Camera preview resumes after incoming callCamera preview active1. Receive voice call 2. Accept call (camera backgrounded) 3. End call 4. Return to appPreview restarts automatically, no black frame, shutter button functional

This table already gives you twenty solid positive cases. Feel free to add more for specific features like live filters, time‑lapse, or HDR bracketing.

Negative and Error‑Handling Test Cases

Negative testing proves that your app behaves correctly when something goes wrong. Camera integration fails in many ways: missing hardware, permission denial, driver crashes, or unexpected OS behavior. Structure negative cases similarly to positives, but focus on the *invalid* input or *unexpected* state.

IDTitlePreconditionsStepsExpected Result
TC‑CAM‑N01App handles missing camera hardwareDevice without camera (e.g., certain Android TV builds)1. Launch app 2. Navigate to camera featureApp shows a clear message “No camera available” and disables related UI
TC‑CAM‑N02Graceful degradation when camera service crashesCamera preview active, force stop media server via adb1. adb shell stop mediacodec 2. Try to capture photoApp receives error callback, shows toast “Camera unavailable, try again”, does not crash
TC‑CAM‑N03Denied permission and persistently blocks cameraPermission denied, “Don’t ask again” selected1. Attempt to open camera 2. System does not show dialogApp displays inline permission rationale and a button to open Settings
TC‑CAM‑N04Invalid picture size requestCamera supports list of sizes, request unsupported size (e.g., 9999×9999)1. Configure capture request with invalid size 2. Initiate captureCamera API returns error, app falls back to nearest supported size or shows error
TC‑CAM‑N05Concurrent access from two app componentsTwo fragments both trying to start camera simultaneously1. Fragment A opens camera 2. Without releasing, Fragment B attempts sameSecond attempt receives CAMERA_ERROR_CAMERA_IN_USE, app logs and notifies user
TC‑CAM‑N06Storage write‑permission missingStorage permission denied, camera permission granted1. Take photo 2. Camera returns image bytesApp cannot write file, shows “Unable to save photo – grant storage permission”
TC‑CAM‑N07Video encoder unavailableDevice lacks hardware H.264 encoder (rare on very old devices)1. Select video mode 2. Press recordApp falls back to software encoder if available, or shows “Video recording not supported”
TC‑CAM‑N08Preview surface destroyed mid‑capturePreview surface (SurfaceView) destroyed while autofocus running1. Start autofocus 2. Immediately call surfaceHolder.removeCallbackAutofocus callback receives error, app does not leak resources, preview stops cleanly
TC‑CAM‑N09Malformed QR code (partial)Camera pointed at a QR code missing finder pattern1. Hold device at angle causing partial view 2. WaitScanner returns no result, UI shows “Try again” after timeout
TC‑CAM‑N10Excessive zoom beyond hardware limitsRequest zoom ratio > max supported (e.g., 10× on a 2× device)1. Set zoom to 10× 2. Attempt to captureCamera clamps to max supported zoom, app logs warning, image captured at max zoom
TC‑CAM‑N11Battery critically low (< 5 %)Device battery at 4 %1. Attempt video recordingApp blocks start, shows low battery warning, suggests charging
TC‑CAM‑N12Overheating throttlingDevice temperature > 40 °C (simulate via stress app)1. Start 4K video recording 2. Monitor frame rateFrame rate drops to maintain thermal limit, app shows notification “Recording may be limited due to temperature”
TC‑CAM‑N13Permission dialog dismissed by back pressPermission dialog showing1. Press back button instead of Allow/DenyDialog dismissed, app treats as denial and shows rationale
TC‑CAM‑N14Camera app hijacked by malicious overlayOverlay app with TYPE_APPLICATION_OVERLAY covering preview1. Launch camera 2. Overlay displays fake buttonApp detects touch outside preview area, prevents accidental actions, logs security event
TC‑CAM‑N15Unsupported MIME type for image captureRequest to save as RAW when device only supports JPEG1. Set output format to RAW 2. CaptureCamera API returns error, app falls back to JPEG or notifies user
TC‑CAM‑N16Audio source unavailable for videoMic muted via accessibility service1. Start video recording with audio enabled 2. Check audio trackAudio track is silent but file is valid; app logs warning
TC‑CAM‑N17File name collision handlingAttempt to save photo with existing filename in app folder1. Take photo named “IMG_0001.jpg” (pre‑existing) 2. 2.App renames file 2. Attempt second capture with same nameApp either auto‑increments suffix (IMG_0001_01.jpg) or prompts user to replace
TC‑CAM‑N18Camera preview orientation lock conflictApp forces portrait, but user has auto‑rotate enabled and device in landscape1. Open camera in portrait mode 2. Rotate device to landscapePreview stays portrait, UI letterboxes correctly, no stretching
TC‑CAM‑N19External storage removed mid‑saveSD card ejected while writing video file1. Start recording to external SD 2. Eject card after 5 sRecording stops, app throws IOException, shows “Storage removed – recording stopped”
TC‑CAM‑N20Intent‑based camera picker returns null dataThird‑party gallery app returns empty data on pick1. Launch intent ACTION_IMAGE_CAPTURE 2. Receive result with data=nullApp handles null gracefully, shows “No image selected” toast

These negative cases expose failure modes that often slip through ad‑hoc testing. Pair each with a logging strategy so you can verify that the correct error path was taken.

Boundary, Stress, and Performance Edge Cases

Beyond functional correctness, camera integration is sensitive to resource limits and timing. Boundary tests push numeric inputs to their extremes; stress tests run the camera repeatedly to uncover leaks or thermal throttling; performance tests measure latency, frame rate, and battery impact.

Boundary Cases

IDTitlePreconditionsStepsExpected Result
TC‑CAM‑B01Minimum supported picture sizeDevice reports min size 320×2401. Configure capture with 320×240 2. Capture photoImage saved, dimensions exactly 320×240
TC‑CAM‑B02Maximum supported picture sizeDevice reports max size 4000×30001. Configure capture with 4000×3000 2. Capture photoImage saved, dimensions 4000×3000, no down‑sampling unless forced
TC‑CAM‑B03Minimum video durationVideo mode allows 0.5 s clips1. Start recording 2. Stop after 0.5 sFile created, duration 0.5 ± 0.05 s, valid moov atom
TC‑CAM‑B04Maximum video duration before file splitFile system limits each video to 4 GB (FAT32)1. Start recording at 1080p30 2. Record until split occurs (~ 22 min)Two files created, each ≤ 4 GB, timestamps continuous
TC‑CAM‑B05Zoom step granularityZoom control supports 0.1× increments1. Set zoom to 1.0× 2. Increment to 1.1× 3. CapturePreview scales accordingly, captured image reflects 1.1× zoom
TC‑CAM‑B06Exposure compensation rangeEV range –2 to +2 in steps of 0.331. Set EV to –2 2. Capture 3. Set EV to +2 4. CaptureHistogram shift measurable, no clipping at extremes
TC‑CAM‑B07Frame rate selectionCamera lists 15, 30, 60 fps options1. Select 15 fps 2. Record 5 s 3. Verify frame count ≈ 75Same for 30 fps (≈ 90 frames) and 60 fps (≈ 180 frames)
TC‑CAM‑B08Focus distance limitsMinimum focus distance 10 cm, macro mode 2 cm1. Place object at 2 cm, enable macro 2. CaptureImage in focus, no blur due to minimum distance violation
TC‑CAM‑B09ISO rangeAuto ISO 100‑6400, manual 100‑128001. Set ISO to 100 2. Capture low‑light scene (expect long exposure) 2. Set ISO to 12800 3. Capture same sceneHigher ISO image brighter, noise increase measurable
TC‑CAM‑B10Shutter speed limitsMinimum 1/8000 s, maximum 2 s1. Set shutter speed to 1/8000 s 2. Capture bright scene (expect frozen motion) 2. Set to 2 s 3. Capture dark scene (expect light trails)Images respect exposure times, no overexposure/underexposure beyond sensor limits

Stress Cases

Stress testing aims to reveal resource leaks, memory growth, or gradual performance degradation. Run each scenario for a high number of iterations (e.g., 50‑100 cycles) and monitor key metrics via adb shell dumpsys meminfo, CPU usage, and battery stats.

IDTitlePreconditionsStepsExpected Result
TC‑CAM‑S01Repeated photo capture leak testCamera permission granted, storage emptyLoop 100×: open camera → capture photo → close preview → force garbage collectionMemory growth < 5 MB, no increase in native heap, file count matches iterations
TC‑CAM‑S02Long‑running video record stressBattery > 80 %, storage > 2 GB freeRecord 1080p30 video for 30 minutes, pause 1 min, resume, repeat 5 timesNo dropped frames > 2 % of total, file integrity checkpoints, no crash, battery drain within expected range (~ 15 % per hour)
TC‑CAM‑S03Rapid orientation flip stressCamera preview activeFlip device 90° left/right every 0.5 s for 2 minutesPreview stays upright, UI does not flicker, no ANR
TC‑CAM‑S04Concurrent camera + sensor stressCamera preview + accelerometer + gyroscope activeRun sensor‑heavy app (e.g., AR navigation) while capturing photos every 5 s for 15 minutesPhoto capture success rate > 98 %, sensor data timestamps consistent
TC‑CAM‑S05Storage full gradual fillStart with 200 MB freeRepeatedly capture 5 MB photos until < 10 MB free, then attempt one more captureApp shows storage‑full warning before crash, no corrupted files
TC‑CAM‑S06Permission toggle stressApp has camera permissionToggle permission off/on via Settings 20× while app is in foregroundEach transition handled: preview stops on denial, restarts on grant, no leaked Camera objects
TC‑CAM‑S07External accessory plug/unplugUSB‑C microphone attachedRecord video, plug/unplug mic 10× during recordingAudio track switches seamlessly, no gaps > 10 ms, no crashes
TC‑CAM‑S08Intent‑based picker stressUse system picker to choose image from galleryLaunch picker 5× each timePicker crashesLaunch picker 30× rapidly, select image each timeApp receives result each time, no ActivityNotFoundException
TC‑CAM‑S09Battery drain measurementFully charged deviceRun a script that takes a photo every 10 s for 1 hourBattery used < 12 % (baseline for camera usage)
TC‑CAM‑S10Thermal throttling observationDevice at ambient 22 °CRun 4K video recording for 20 minutes, log CPU temperature every 10 sTemperature stabilizes below throttling threshold (~ 80 °C), frame rate drops gracefully if limit exceeded

Performance Cases

Performance testing validates that the camera meets user‑experience expectations for latency and smoothness. Use instrumentation like adb shell cmd gfxinfo or adb shell dumpsys gfxinfo to measure frame times.

IDTitlePreconditionsStepsExpected Result
TC‑CAM‑P01Preview startup latencyCamera permission already granted1. Tap camera launch button 2. Measure time to first preview frameLatency ≤ 800 ms on mid‑tier device, ≤ 500 ms on flagship
TC‑CAM‑P02Capture‑to‑save latencyPreview active, auto‑focus locked1. Tap shutter 2. Measure time until file write completeLatency ≤ 1.2 s for JPEG 1920×1080 Q85
TC‑CAM‑P03Focus acquisition timeScene with high contrast target1. Initiate focus (tap to focus) 2. Measure time until focus locked≤ 400 ms
TC‑CAM‑P04Frame‑rate stability during recording1080p30 video modeRecord 10 s, compute average frame time33.3 ms ± 2 ms (≥ 29 fps effective)
TC‑CAM‑P05Battery impact per minuteIdle baseline measuredRun video recording for 5 minutes, measure % dropDrop ≤ 8 % per minute on typical device
TC‑CAM‑P06Memory footprint during previewPreview active, no captureSample memory usage via dumpsys meminfoHeap growth stable (< 10 MB increase)
TC‑CAM‑P07CPU usage during idle previewPreview active, no interactiontop -m 10 -t -n 1Camera process < 5 % CPU on idle preview
TC‑CAM‑P08AR overlay render timeAR session active, model < 500 polyMeasure time from frame arrival to model draw≤ 16 ms (to maintain 60 fps)
TC‑CAM‑P09QR code decode latencyClear QR code at 15 cm distanceStart timer when code enters FOV, stop when decode callback fires≤ 300 ms
TC‑CAM‑P10Video encoder bitrate accuracyTarget bitrate 8 Mbps for 1080p30Encode 10 s clip, compute average bitrate via ffprobeWithin ± 10 % of target

These performance numbers become your acceptance criteria; track them in a test dashboard to catch regressions early.

Device‑Specific and OS‑Level Variations

Camera behavior diverges across manufacturers, Android versions, and iOS releases. Your test matrix must account for these variables, either by parameterizing test data or by maintaining device‑specific test suites.

Android Fragmentation Points

VariableImpact on CameraTest Strategy
Camera2 API levelLEGACY vs LIMITED vs FULL vs LEVEL_3 determines available controls (manual focus, ISO, exposure time)Create a capability matrix; run the same functional test on each level, skipping unsupported steps (mark as N/A)
Vendor‑specific extensions (e.g., Samsung’s ISOCELL, Google’s HDR+)May add extra modes like “Night Sight” or “Portrait”Add optional test cases that are enabled only when the extension is present (detect via PackageManager.hasSystemFeature)
Screen density & aspect ratioPreview SurfaceView layout may stretch or letterbox incorrectlyValidate preview aspect ratio matches sensor aspect ratio on multiple densities (ldpi, mdpi, hdpi, xhdpi, xxhdpi, xxxhdpi)
Storage access model (Scoped Storage, legacy)Determines where you can write media filesTest both app‑specific directory and, if applicable, shared Pictures directory with proper URI permissions
Intent resolutionSome OEMs replace the stock camera picker with a custom oneVerify that ACTION_IMAGE_CAPTURE and ACTION_VIDEO_CAPTURE return expected data URIs on each OEM build
Background location & camera restrictions (Android 12+)Apps may be prevented from using camera while in backgroundTest that background camera use throws SecurityException and is handled gracefully
Java/Kotlin vs. Native (NDK)If you use native camera via OpenSL or libcamera, JNI overhead may differRun performance tests on both Java and native implementations

iOS Specific Points

VariableImpactTest Strategy
AVFoundation capture session configurationPresets (photo, video, high‑frame‑rate) affect available resolutionsParameterize test by AVCaptureSessionPreset and verify each yields expected dimensions
Camera authorization status (AVAuthorizationStatus)Denied, restricted, notDetermined, authorized flowsExercise all four states, verify UI prompts and fallback messages
Live PhotosAdds a MOV resource alongside JPEGCapture Live Photo, verify both assets present and correctly linked
Depth data (Portrait mode)Requires dual‑camera or LiDARWhen depth available, capture depth map and verify its resolution matches preview
ProRAW (iPhone 12 Pro + )Produces DNG with larger file sizeEnable ProRAW, capture, validate DNG header and size > 10 MB
Metal‑based processingCustom filters via Metal shadersRun a custom Metal filter on preview, measure frame‑time impact
Background audio interruptionIncoming call pauses capture sessionSimulate call, verify session pauses and resumes without losing buffer

Cross‑Platform Web Camera (getUserMedia)

When testing a web application that uses navigator.mediaDevices.getUserMedia, the matrix shifts to browser and OS combos.

VariableImpactTest Strategy
Browser (Chrome, Firefox, Safari, Edge)Different implementation of constraints, varying support for echoCancellation, noiseSuppressionRun same test script in each browser, capture console errors
OS (Windows, macOS, Linux, Android, iOS)Camera permission UI differs; some OSes hide the camera indicatorVerify permission prompts appear correctly and that the indicator (LED or OS bar) shows when active
Device orientationMobile browsers may lock orientation based on CSSTest portrait vs. landscape locking behavior
HTTPS requirementgetUserMedia requires secure context (localhost exempt)Confirm failure on HTTP, success on HTTPS or localhost
Frame rate constraintsSome browsers cap at 30 fps even if device can do 60Verify requested vs. actual frame rate via videoTrack.getCapabilities()
Audio‑video couplingSome browsers require audio track even if you only want videoTest providing {video:true, audio:false} and check if audio track is omitted
Screen share vs. cameragetDisplayMedia vs. getUserMediaEnsure your code does not mistakenly request screen share when camera intended

By structuring your test cases with parameters (device API level, camera capability flags, browser version), you can generate a combinatorial test suites automatically using tool or TestNG** data providers.

Traceability, Prioritization, and Test Management

A test case is only as valuable as its ability to be linked back to a requirement and to be prioritized according to risk. Establish a lightweight but rigorous process.

Traceability Matrix

Create a simple spreadsheet or use a feature of your test management tool with these columns:

Requirement IDRequirement DescriptionTest Case IDsStatus (Pass/Fail/Blocked)Last RunComments
REQ‑CAM‑01Request CAMERA permission before previewTC‑CAM‑001, TC‑CAM‑N03Pass2025‑10‑28

Test Your App Autonomously

Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts.

Try SUSA Free