How to Write Test Cases for Avatar Upload (With Examples)

How to Write Test Cases for Avatar Upload (With Examples)

April 15, 2026 · 16 min read · How-To Guides

How to Write Test Cases for Avatar Upload (With Examples)

Avatar upload is a common feature in modern applications, yet it hides a surprising amount of complexity. Getting the test coverage right means you can catch crashes, security holes, accessibility barriers, and usability friction before they reach users. This guide walks you through the full process of creating high‑signal test cases for avatar upload, from anatomy and categorization to a concrete matrix of 20+ examples, data preparation, prioritization, traceability, and a blend of manual and autonomous techniques. By the end you will have a ready‑to‑use test suite that you can execute today and evolve tomorrow.

How to Write Test Cases for Avatar Upload (With Examples): Overview

Before diving into details, establish why avatar upload warrants dedicated test effort. The feature typically accepts an image file, validates its type and size, stores it, associates it with a user profile, and displays it in various UI contexts (profile header, chat thumbnail, comment avatar). Each step introduces failure points: incorrect MIME‑type detection, buffer overflows during decoding, storage quota exceeded, CDN caching issues, loss of EXIF orientation, or accessibility problems when the image lacks alternative text. A well‑designed test suite exercises all of these paths, giving you confidence that the function behaves correctly under normal, erroneous, and hostile conditions.

Start by gathering the functional specification, any UI mockups, and non‑functional requirements (e.g., maximum file size 5 MB, allowed formats JPEG/PNG/WebP, must preserve aspect ratio, must be WCAG 2.1 AA compliant for contrast when overlaid on UI). Write each requirement as a testable statement; later you will map test cases back to these statements to ensure traceability.

How to Write Test Cases for Avatar Upload (With Examples): Anatomy of a Test Case

A test case is more than a list of steps; it is a reproducible artifact that communicates intent, preconditions, actions, and verification criteria. Use the following fields consistently:

Keep the wording imperative and free of ambiguity. Avoid compound steps like “Upload the image and verify it appears”; split into separate steps for upload and verification. This granularity simplifies debugging when a step fails.

How to Write Test Cases for Avatar Upload (With Examples): Categorizing Test Cases

Organize your cases into logical buckets so you can prioritize, review, and maintain them efficiently. The following categories are useful for avatar upload:

Positive (Happy‑Path) Cases

These verify that the feature works as intended when all inputs conform to the specification. Examples include uploading a valid JPEG of 2 MB, a PNG with transparency, or a WebP file that meets size limits. Positive cases also cover successful display across different UI densities and theme variations.

Negative (Invalid‑Input) Cases

These test the system’s reaction to data that violates one or more constraints. Typical negative scenarios involve:

Boundary and Edge Cases

Boundary testing focuses on values at the limits of allowed ranges. For avatar upload, test:

Security‑Focused Cases

Avatar upload can be an attack vector. Test for:

Accessibility and Internationalization Cases

Ensure the uploaded avatar does not create accessibility barriers:

Performance and Load Cases

Although avatar upload is infrequent per user, bursts can occur (e.g., during a profile‑picture‑change campaign). Measure:

By defining these categories early, you can allocate test effort according to risk and ensure that no class of defects is overlooked.

How to Write Test Cases for Avatar Upload (With Examples): Building the Test Matrix

Below is a concrete set of 22 test cases that cover the categories described. Each row follows the anatomy outlined earlier. For brevity, the “Test Data” column summarizes the key attributes; the full file objects are stored in a test‑data repository (e.g., Git‑LFS or a dedicated S3 bucket). The matrix can be imported into most test‑management tools (TestRail, Zephyr, Xray) via CSV.

IDTitlePreconditionsStepsExpected Result
AVT‑001Valid JPEG under size limit uploads successfullyUser logged in, on profile edit page, storage quota >10 MB1. Click “Change Avatar”. 2. Choose file avatar.jpg (2 MB, 400×400). 3. Press “Upload”.Avatar image appears in header, file stored as avatar.jpg, no error toast, success message shown.
AVT‑002Valid PNG with transparency uploads successfullySame as AVT‑0011. Click “Change Avatar”. 2. Choose file avatar.png (1.8 MB, 350×350, alpha channel). 3. Press “Upload”.Avatar displayed preserving translucency, no background fill, success message.
AVT‑003Valid WebP under limit uploads successfullySame as AVT‑0011. Click “Change Avatar”. 2. Choose file avatar.webp (1.2 MB, 500×500). 3. Press “Upload”.Avatar shown, file stored as WebP, success message.
AVT‑004File exactly at size limit (5 MB) uploads successfullySame as AVT‑0011. Click “Change Avatar”. 2. Choose file avatar_5mb.jpg (5 MB exactly, 2000×2000). 3. Press “Upload”.Upload completes, avatar displayed, no size‑limit error.
AVT‑005File 1 byte over limit rejectedSame as AVT‑0011. Click “Change Avatar”. 2. Choose file avatar_5mb_plus1.jpg (5 000 001 bytes). 3. Press “Upload”.Upload blocked, error toast: “File exceeds 5 MB limit”. No avatar change.
AVT‑006Invalid file type (.gif) rejectedSame as AVT‑0011. Click “Change Avatar”. 2. Choose file avatar.gif (valid GIF, 300 KB). 3. Press “Upload”.Upload blocked, error toast: “Only JPEG, PNG, WebP allowed”.
AVT‑007Invalid file type (.exe) rejectedSame as AVT‑0011. Click “Change Avatar”. 2. Choose file malicious.exe (renamed to avatar.jpg but actual content is PE executable). 3. Press “Upload”.Upload blocked, error toast: “Invalid file type”. File not stored.
AVT‑008Zero‑byte file rejectedSame as AVT‑0011. Click “Change Avatar”. 2. Choose file empty.jpg (0 bytes). 3. Press “Upload”.Upload blocked, error toast: “File is empty”.
AVT‑009Corrupted JPEG (truncated) rejectedSame as AVT‑0011. Click “Change Avatar”. 2. Choose file corrupt.jpg (valid JPEG header, truncated body). 3. Press “Upload”.Upload blocked, error toast: “Unable to read image file”.
AVT‑010File with mismatched extension and content rejectedSame as AVT‑0011. Click “Change Avatar”. 2. Choose file fake.jpg (plain text “not an image”). 3. Press “Upload”.Upload blocked, error toast: “File is not a valid image”.
AVT‑011Very small dimensions (10×10) acceptedSame as AVT‑0011. Click “Change Avatar”. 2. Choose file tiny.jpg (10 × 10 px, 0.5 KB). 3. Press “Upload”.Avatar displayed (may appear pixelated), success message.
AVT‑012Maximum allowed dimensions (2000×2000) acceptedSame as AVT‑0011. Click “Change Avatar”. 2. Choose file maxdim.jpg (2000 × 2000 px, 4.8 MB). 3. Press “Upload”.Avatar displayed, success message.
AVT‑013Dimensions exceeding limit (2001×2001) rejectedSame as AVT‑0011. Click “Change Avatar”. 2. Choose file overdim.jpg (2001 × 2001 px, 5 MB). 3. Press “Upload”.Upload blocked, error toast: “Image dimensions exceed maximum allowed”.
AVT‑014File name with Unicode characters acceptedSame as AVT‑0011. Click “Change Avatar”. 2. Choose file αβγ_avatar.jpg (valid JPEG, 1.2 MB). 3. Press “Upload”.Avatar uploaded successfully, stored with original filename, success message.
AVT‑015Extremely long file name (255 chars) rejected (if limit)Same as AVT‑0011. Click “Change Avatar”. 2. Choose file a…a.jpg (name 255 chars, valid JPEG). 3. Press “Upload”.Upload blocked, error toast: “File name too long”.
AVT‑016Concurrent upload attempts – only last winsTwo browser tabs logged in as same user, both on profile page.Tab A: select avatarA.jpg (1 MB). Tab B: select avatarB.jpg (1 MB).
1. In Tab A press Upload. 2. Immediately after, in Tab B press Upload.
Final avatar shown is the one from Tab B; no error or crash; only one avatar record stored.
AVT‑017Network dropout mid‑upload – retry or clear stateSimulated throttling to 50 kbps after 50 % of file sent.1. Click “Change Avatar”. 2. Choose avatar.jpg (2 MB). 3. Press Upload. 3. Wait until upload stalls, then restore network.Upload either completes successfully after retry or shows clear error and leaves profile unchanged (no partial avatar).
AVT‑018Image with EXIF orientation tag displayed correctlySame as AVT‑0011. Click “Change Avatar”. 2. Choose oriented.jpg (image captured sideways, EXIF Orientation=6). 3. Press “Upload”.Avatar appears upright (orientation applied), success message.
AVT‑019Image containing embedded script in metadata is sanitizedSame as AVT‑0011. Click “Change Avatar”. 2. Choose script_meta.jpg (valid JPEG, EXIF UserComment contains ). 3. Press “Upload”.Upload succeeds, but when avatar rendered in profile, script is not executed; no alert shown.
AVT‑020Polyglot GIFAR (GIF+JPEG) rejectedSame as AVT‑0011. Click “Change Avatar”. 2. Choose gifar.gif (file that is both a valid GIF and contains JPEG executable payload). 3. Press “Upload”.Upload blocked, error toast: “Invalid file type”.
AVT‑021Filename path traversal attempt blockedSame as AVT‑0011. Click “Change Avatar”. 2. Choose file ../../etc/passwd.jpg (valid JPEG). 3. Press “Upload”.Upload blocked, error toast: “Invalid file name”. No storage outside intended directory.
AVT‑022Avatar accessible name/alt text can be set (if supported)Same as AVT‑001, platform allows user‑provided description.1. Click “Change Avatar”. 2. Choose avatar.jpg. 3. In description field enter “Smiling user”. 4. Press Upload.Avatar displayed; inspection of DOM shows alt="Smiling user" (or aria-label). Success message.
AVT‑023Avatar contrast over light and dark backgrounds meets WCAG AASame as AVT‑001, theme toggle available.1. Upload a mid‑tone avatar (gray.jpg). 2. Switch theme to light, verify contrast ratio ≥4.5:1. 3. Switch theme to dark, verify same.Contrast ratios meet WCAG AA for both themes; no accessibility warning in audit tools.
AVT‑024Large burst of uploads does not degrade server response timeTest rig with 50 virtual users, each uploading a 1 MB avatar.1. Start load test. 2. Monitor average upload latency and server CPU.Average latency stays <2 s, CPU <70 % peak, no HTTP 500 responses.

How to use the table

How to Write Test Cases for Avatar Upload (With Examples): Data Setup and Test Data Management

Effective avatar‑upload testing hinges on realistic, varied, and controllable test data. Treat your image assets as first‑class test artifacts.

Sourcing Base Images

Start with a small library of reference images that cover the allowed formats and a range of visual properties:

Include at least one image that contains EXIF orientation tags, one with embedded XMP metadata, and one that is deliberately corrupted (e.g., truncate a JPEG after the SOS marker).

Generating Boundary Variants

Use command‑line tools to derive size‑ and dimension‑based variants from a base image:


# Reduce to exact 5 MB limit (assuming base is larger)
dd if=base.jpg of=avatar_5mb.jpg bs=1M count=5
# Create a 10×10 thumbnail
convert base.jpg -resize 10x10! tiny.jpg
# Create a 2001×2001 oversize image (pad with white)
convert -size 2001x2001 xc:white overdim.jpg
# Insert a known EXIF tag
exiftool -Orientation=6 -overwrite_original oriented.jpg

Store the generated files alongside the base images, naming them according to the test‑case ID they support.

Crafting Malicious Payloads

For security‑focused cases, create polyglot or metadata‑injected files using proven techniques:

Managing Test Data in Version Control

Large binary files bloat Git histories. Use Git‑LFS or an artifact repository (e.g., Nexus, Artifactory) and reference the files by SHA‑256 checksum in a manifest:


# testdata_manifest.yaml
AVT-001:
  path: avatars/avatar.jpg
  sha256: 3a7f9c1e...
AVT-005:
  path: avatars/avatar_5mb_plus1.jpg
  sha256: f4e2b8d9...

Automated tests can download the file, verify its hash, then proceed. This ensures reproducibility across environments and prevents drift.

Data Cleanup

After each test run, decide whether to retain uploaded avatars for audit or delete them to keep storage quotas realistic. Implement a teardown step that calls the API DELETE /users/{id}/avatar or invokes a admin cleanup script. Log the deletion outcome for traceability.

How to Write Test Cases for Avatar Upload (With Examples): Prioritization and Risk‑Based Testing

Not all test cases carry equal weight. Apply a simple risk matrix to order execution and allocate automation effort.

Impact × Likelihood Scoring

Assign each test case an Impact (1‑5) based on potential user or business harm if the defect escapes, and a Likelihood (1‑5) based on historical defect density or complexity of the code path. Compute Risk Score = Impact × Likelihood (range 1‑25). Example scoring:

IDImpactLikelihoodRisk ScoreRationale
AVT‑005 (oversize)4416Users often try to upload large photos; failure leads to confusing error or silent drop.
AVT‑007 (exe)5210Malicious upload is rare but high‑impact (code execution).
AVT‑018 (EXIF orientation)339Misoriented avatars degrade UX but are not catastrophic.
AVT‑022 (alt text)248Accessibility issue affects a subset of users; likelihood high due to frequent UI changes.
AVT‑024 (burst load)326Load spikes are infrequent; performance degradation is moderate.

Prioritize execution in descending Risk Score. For automation, automate all cases with a score ≥12 first; the remainder can remain manual or be automated later as capacity allows.

Test‑Execution Order

Within a test suite, arrange cases so that setup/teardown overhead is minimized:

  1. Positive baseline (AVT‑001‑AVT‑004) to confirm the system is healthy.
  2. Invalid‑type and size limits (AVT‑005‑AVT‑008) – quick negative checks.
  3. Corruption & mutilation (AVT‑009‑AVT‑011).
  4. Boundary dimensions (AVT‑012‑AVT‑013).
  5. Filename & Unicode (AVT‑014‑AVT‑015).
  6. Concurrency & network (AVT‑016‑AVT‑017).
  7. Security & metadata (AVT‑018‑AVT‑021).
  8. Accessibility & i18n (AVT‑022‑AVT‑023).
  9. Load/performance (AVT‑024) – run last, possibly in a separate performance pipeline.

If a test fails, halt the suite and investigate; continuing may mask root causes.

How to Write Test Cases for Avatar Upload (With Examples): Traceability to Requirements and User Stories

Traceability ensures that every requirement has at least one verifying test case and that test effort is aligned with stakeholder expectations.

Mapping Process

  1. Extract requirement IDs from the specification document (e.g., REQ‑AVT‑01: “System shall accept JPEG, PNG, WebP files up to 5 MB.”).
  2. Create a traceability matrix (simple two‑column table) linking each requirement to the test case IDs that verify it.
  3. Update the matrix whenever a requirement changes or a new test is added.

#### Example Traceability Table

Requirement IDDescriptionVerifying Test Cases
REQ‑AVT‑01Accept JPEG/PNG/WebP ≤5 MBAVT‑001, AVT‑002, AVT‑003, AVT‑004
REQ‑AVT‑02Reject files >5 MBAVT‑005
REQ‑AVT‑03Reject non‑allowlisted extensionsAVT‑006, AVT‑007
REQ‑AVT‑04Handle zero‑byte and corrupted files gracefullyAVT‑008, AVT‑009, AVT‑010
REQ‑AVT‑05Preserve EXIF orientationAVT‑018
REQ‑AVT‑06Sanitize metadata (no script execution)AVT‑019
REQ‑AVT‑07Block path‑traversal filenamesAVT‑021
REQ‑AVT‑08Support user‑provided alt text/aria‑labelAVT‑022
REQ‑AVT‑09Maintain WCAG AA contrast on light/dark themesAVT‑023
REQ‑AVT‑10Sustain ≤2 s latency under 50 concurrent 1 MB uploadsAVT‑024

Linking to User Stories

In Agile environments, user stories often capture the same intent. For instance:

Map each acceptance criterion to one or more requirement IDs, and thereby to test cases. This creates a clear path from story → requirement → test case → automated script.

Maintain the traceability matrix in a lightweight format (e.g., a Google Sheet or a markdown file in the repo). Many test‑management tools can import such matrices and show coverage percentages directly on the requirement tree.

How to Write Test Cases for Avatar Upload (With Examples): Manual vs Automated Approaches

Both manual exploratory testing and automated regression have roles. Use manual testing to discover unexpected behaviors, especially those tied to device‑specific rendering or accessibility screen‑reader quirks. Automate the repeatable, data‑driven checks to gain fast feedback on every commit.

When to Keep a Test Manual

Automating the Core Matrix

Most of the cases in the table lend themselves to scripted execution. Below are concise examples for Android (using Appium) and for a web UI (using Playwright). Adjust the selectors and endpoints to match your application.

#### Android Appium (Java)


public class AvatarUploadTest {
    private AppiumDriver<MobileElement> driver;
    private final String uploadBtn = "accessibility_id:Change Avatar";
    private final String fileInput = "xpath://android.widget.EditText[@resource-id='filePicker']";
    private final String successToast = "xpath://android.widget.Toast[contains(@text,'Upload successful')]";

    @BeforeEach
    void setUp() {
        driver = new AndroidDriver<>(new URL("http://localhost:4723/wd/hub"), capabilities);
    }

    @AfterEach
    void tearDown() {
        if (driver != null) driver.quit();
    }

    void uploadFile(String localPath, String description) {
        driver.findElement(By.id(uploadBtn)).click();
        // Assuming a native file chooser; on Android you may need to use adb push + intent
        PushFile.push(localPath, "/sdcard/Download/");
        driver.findElement(By.xpath(fileInput)).sendKeys("/sdcard/Download/" + new File(localPath).getName());
        if (!description.isEmpty()) {
            driver.findElement(By.id("description_field")).sendKeys(description);
        }
        driver.findElement(By.id("upload_button")).click();
        WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(15));
        wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(successToast)));
    }

    @Test
    void testValidJpegUnderLimit() {
        uploadFile("src/test/resources/avatars/avatar.jpg", "");
        // Additional assertions: verify avatar ImageView src, check DB via API, etc.
    }

    @Test
    void testFileOverLimitShowsError() {
        uploadFile("src/test/resources/avatars/avatar_5mb_plus1.jpg", "");
        // Expect error toast
        WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
        wait.until(ExpectedConditions.visibilityOfElementLocated(
                By.xpath("//android.widget.Toast[contains(@text,'exceeds 5 MB')]")));
    }
}

*Notes*:

#### Web Playwright (TypeScript)


import { test, expect } from '@playwright/test';

test.describe('Avatar upload', () => {
  test.beforeEach(async ({ page }) => {
    await page.loginViaApi('testUser', 'password'); // custom helper
    await page.goto('/profile/edit');
  });

  const uploadSelector = 'input[type="file"][accept="image/*"]';
  const previewImg = 'img[data-testid="avatar-preview"]';
  const successMsg = 'text=Avatar updated successfully';

  async function uploadFile(filePath: string, altText?: string) {
    const [fileChooser] = await Promise.all([
      page.waitForEvent('filechooser'),
      page.click('button:has-text("Change Avatar")')
    ]);
    await fileChooser.setFile(filePath);
    if (altText) {
      await page.fill('textarea[aria-label="Description"]', altText);
    }
    await page.click('button:has-text("Upload")');
    await expect(page.locator(successMsg)).toBeVisible({ timeout: 8000 });
  }

  test('valid PNG with transparency', async ({ page }) => {
    await uploadFile('tests/fixtures/avatars/avatar.png');
    const preview = page.locator(previewImg);
    await expect(preview).toHaveAttribute('src', /avatar\.png/);
    // Optionally compute checksum of downloaded image to confirm fidelity
  });

  test('file over 5 MB shows error', async ({ page }) => {
    await uploadFile('tests/fixtures/avatars/avatar_5mb_plus1.jpg');
    await expect(page.locator('text=File exceeds 5 MB limit')).toBeVisible();
    await expect(page.locator(previewImg)).toHaveCount(0); // no preview shown
  });

  // Add more tests for EXIF orientation, metadata sanitization, etc.
});

*Notes*:

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