Your profile

One profile for every MSDEVBUILD site. Only you can see it, and the site owner if you write in.

Lesson 25 of 30
❮Prev Next❯

Unit Tests, Integration Tests and Edge Cases with Copilot

Module 5: Productivity ⏱ 10 min read Updated

Your note

My notes for this lesson

Select any text in the lesson to highlight it or add a note. Saved in this browser.

    No highlights yet. Select a sentence in the lesson, then pick a colour or add a note.

    All my bookmarks and notes

    Reading settings

    For every lesson, saved in this browser.

    Text size
    Line spacing
    Font

    With IaaS you rent the virtual machine. Microsoft looks after the building, power and hardware; you patch the operating system.

    30-second answer

    Select the code and run /tests in Copilot Chat (or ask agent mode) to generate unit tests, which check one function in isolation. Name the edge cases you care about (unknown input, missing values, zero, empty lists, very large numbers, boundaries) and ask Copilot to suggest ones you missed. Check every test has a clear assertion of one behaviour with an exact expected value. Integration tests check pieces working together, such as an API route calling the discount module; ask Copilot for the setup and teardown too. Run the tests: when a generated test fails, decide whether the code has a bug or the test is wrong, then fix the right one.

    Simulate it » No Azure account needed

    Exam objective: 5.2.1 Generate unit and integration tests. 5.2.2 Identify edge cases and write assertions. (Skills measured as of August 7, 2026)

    Simulations

    Feel it before you read it. No account needed, nothing leaves this page.

    VS Code & GitHub: Unit tests, integration tests and edge cases Generate tests with edge cases and read the failures.
    </> Embed

    Embed this simulation

    Free for trainers, teachers and bloggers. Paste this into your page:

    Loading…

    Select the code and run <strong>/tests</strong>, naming the <strong>edge cases</strong> you care about. Copilot also suggests ones you missed.

    👆 Click the glowing item on screen to continue

    Read the steps as text
    1. Select the code and run /tests, naming the edge cases you care about. Copilot also suggests ones you missed.
    2. Check the assertions: each test should check one behaviour with a clear expected value. Weak assertions (only “is defined”) prove little.
    3. Integration tests check pieces working together (the API, the discount module, the JSON). Ask Copilot for the setup and teardown too.
    4. Run them. A failing generated test is useful: either the code has a bug or the test is wrong. Decide which, then fix.

    🧪 Simulation for learning. Screens are simplified versions of Visual Studio Code and github.com with GitHub Copilot; names, files and suggestions are examples. Not affiliated with GitHub or Microsoft, and nothing here touches your real account.

    😟 THE PROBLEM

    Coverage is low and the edge cases only show up in production.

    😊 THE SOLUTION

    Generate unit and integration tests with Copilot and check the assertions.

    • Missing edge cases✓ Ask for them by name
    • Weak assertions✓ One clear expected value
    • Pieces fail together✓ Integration tests
    🛠️ Solved with: Tests with Copilot

    Start with a question

    Who's better at thinking of the weird inputs that break your code: you, at the end of a long day, or a tool that has seen millions of test files?

    Honestly, neither on its own. You know what the code is for. Copilot is good at listing the cases people forget.

    On contoso-shop, Asha selected applyDiscount and asked: “/tests applyDiscount: cover unknown codes, no code, 0 and very large totals.” Copilot wrote six tests in seconds. Two failed. Her first thought was “Copilot got it wrong”. It hadn’t. applyDiscount(100, 'NOPE') returned NaN, because CODES['NOPE'] is undefined. That bug had been in production for months. The failing test was the most useful thing on the screen.

    Explain it like I’m 10

    Visual: tests that find a bug in motion

    Watch Copilot write tests with edge cases, two of them fail, and a small fix turns the suite green.

    ▶ Explainer video See it in motion 8 steps · 1 min 50 sec

    An animation of testing with GitHub Copilot in the contoso-shop sample repo. A developer selects applyDiscount and asks /tests with named edge cases, and Copilot suggests more. Six tests are written with exact assertions instead of weak ones. npm test shows two failures: an unknown code and no code return NaN because CODES[code] is undefined. The developer decides the code is wrong, applies a one-line fix with a default of 0, reruns and all six pass. Finally an integration test posts a cart to the API and checks the total of 90.
    Read the video script
    1. Ask for tests, name the edge casesStart by selecting applyDiscount and typing slash tests. Don't just say write tests. Name the awkward inputs you already know: an unknown code, no code, a zero total.
    2. Copilot adds the ones you missedCopilot adds a couple you didn't think of, like a very large total or a lowercase code. Useful, but you decide the rule. Should save10 in lowercase work? That's a business call, not Copilot's.
    3. Six tests, one behaviour eachCopilot writes six tests in the framework the repo already uses. Each one is named after a single behaviour, so when one fails you know exactly what broke.
    4. Assertions that can failNow read the assertions. A weak one only checks the result exists, and it passes even when the maths is wrong. A strong one checks an exact value: one hundred in, one hundred out.
    5. Run them: two failRun npm test. Four pass, two fail. An unknown code and no code both come back as not a number instead of the original total.
    6. Bug in the code, or in the test?This is the moment that matters. Is the code wrong or the test? Read the code: an unknown code gives undefined, and the maths turns that into NaN. The tests are right. They just found a real bug.
    7. Smallest fix, then greenAsk for the smallest fix: default the percentage to zero. Review the one-line diff, run the whole suite again, and now all six pass. Only then do you commit.
    8. Then test the pieces togetherUnit tests check one function at a time. An integration test checks the pieces together: post a cart to the API, and expect a two hundred status and a total of ninety.

    The technical explanation

    Generate unit tests

    Select the function and ask:

    /tests applyDiscount: cover unknown codes, no code, 0 and very large totals

    Copilot writes tests in the framework your project already uses (it reads package.json and existing files in tests/). You can also ask agent mode: “Write unit tests for src/discount.js, run them, and tell me what fails.” It writes the file, asks before running npm test, and reports back. If you keep test rules in .github/instructions/tests.instructions.md with applyTo: "tests/**", Copilot follows them.

    import { test } from 'node:test';
    import assert from 'node:assert/strict';
    import { applyDiscount } from '../src/discount.js';
    
    test('SAVE10 takes 10% off', () => assert.equal(applyDiscount(100, 'SAVE10'), 90));
    test('unknown code leaves the total unchanged', () => assert.equal(applyDiscount(100, 'NOPE'), 100));
    test('no code leaves the total unchanged', () => assert.equal(applyDiscount(100), 100));
    test('empty cart stays at 0', () => assert.equal(applyDiscount(0, 'HALF'), 0));

    Find the edge cases

    Edge cases are where bugs live. Name the ones you know and ask Copilot for more: “What edge cases am I missing for applyDiscount?”

    CategoryFor applyDiscount(total, code)
    Unknown or invalid input'NOPE', lowercase 'save10'
    Missing inputno code, null, empty string
    Zero and boundariestotal 0, a 100% code
    Very large or small1e12, negative totals
    Wrong type'100' as a string

    Copilot is good at producing this list. You decide which behaviours are correct, because only you know the business rule: should a lowercase code work? Should a negative total throw?

    Write assertions that can fail

    An assertion compares the actual result with an exact expected value. Check every generated test for this:

    WeakStrong
    assert.ok(applyDiscount(100, 'SAVE10'))assert.equal(applyDiscount(100, 'SAVE10'), 90)
    “doesn’t throw”“throws a RangeError for a negative total”
    one test checking five thingsfive tests, each named after one behaviour

    A weak test passes even when the code is wrong, which is worse than no test because it looks like coverage. Use arrange, act, assert: set up inputs, call the code, check one result.

    Integration tests

    Unit tests isolate one function. Integration tests check that parts work together: the HTTP route, the cart and discount modules, and the JSON response.

    import request from 'supertest';
    import { app } from '../src/app.js';
    
    test('POST /cart/total applies SAVE10', async () => {
      const res = await request(app)
        .post('/cart/total')
        .send({ items: [{ price: 50, qty: 2 }], code: 'SAVE10' });
      assert.equal(res.status, 200);
      assert.equal(res.body.total, 90);
    });

    Ask Copilot for the setup and teardown too: starting the app, seeding a test database with fake data, cleaning up afterwards. Mocks and stubs keep unit tests isolated; integration tests use the real pieces (or realistic test doubles for external services).

    Read the failures

    $ npm test
    ✔ SAVE10 takes 10% off
    ✖ unknown code leaves the total unchanged   expected 100, got NaN
    ✖ no code leaves the total unchanged        expected 100, got NaN
    ℹ pass 4  fail 2

    A failing generated test means one of two things: the code has a bug or the test expects the wrong behaviour. Here the code is wrong, so ask for the smallest fix (const pct = CODES[code] ?? 0;), read the diff and rerun. Never delete a failing test just to get green.

    Architect level Coverage numbers can lie

    Copilot can push line coverage up quickly, and that’s tempting to celebrate. But coverage only says which lines ran, not whether anything was checked. A test that calls every function and asserts nothing gives high coverage and zero protection. Look at the assertions, try breaking the code on purpose to see if a test fails (the idea behind mutation testing), and keep tests readable so the next person knows what behaviour each one protects.

    Real-world business scenario

    Online retail

    Contoso (fictional)

    The problem
    contoso-shop's discount module had almost no tests. A customer typed a code in lowercase, got a NaN total, and checkout failed for every order using that code until someone noticed hours later.
    What they used
    Copilot Chat /tests with named edge cases for each module, Copilot-drafted supertest integration tests for the checkout API, path-specific test instructions, and a rule that failing generated tests are investigated, not deleted.
    Why that choice
    Copilot listed edge cases the team had skipped, the assertions checked exact values, and the integration tests caught problems between the route and the modules.
    The result
    The next two discount bugs were caught in pull requests by failing tests instead of by customers at checkout.

    When to use it and when not to

    ✓ Use it when…

    • Generating a first set of unit tests for existing code, then reviewing each one.
    • Listing edge cases you might miss and turning them into precise assertions.
    • Drafting integration test setup and teardown for APIs and services.

    ✕ Think twice when…

    • Accepting tests whose assertions can't fail, just to raise coverage.
    • Letting Copilot decide business rules. You decide what the correct behaviour is.

    ↔ Alternatives to consider

    • Write the test first yourself (test-driven development) and let Copilot write the code to pass it.
    • Code scanning and CI checks alongside tests, so security issues are caught too.
    Ready for more?The full lesson adds the technical explanation, when to use it, interview questions and revision notes.

    Test yourself with exercises

    5 original practice questions in the GH-300 style. Pick your answers, then check them. You will see why each option is right or wrong. Score 75% or more and this topic is marked complete.

    Question 1

    Question 1 of 5

    A developer selects the applyDiscount function in Visual Studio Code and wants GitHub Copilot to generate tests for it. Which Copilot Chat slash command should the developer use?

    Question 2

    Question 2 of 5

    GitHub Copilot generates unit tests for a discount function. Two of the tests fail because the function returns NaN for an unknown discount code instead of the original total. What should the developer do?

    Question 3

    Question 3 of 5 · Select 2

    A developer asks GitHub Copilot to identify edge cases for the function applyDiscount(total, code). Which TWO inputs are edge cases?

    Question 4

    Question 4 of 5

    Unit tests for the cart and discount modules pass. However, the checkout API in a test environment returns an incorrect total. Which type of test should the developer ask GitHub Copilot to generate to detect this problem?

    Question 5

    Question 5 of 5

    A developer reviews tests generated by GitHub Copilot. Which assertion most effectively verifies that the SAVE10 code applies a 10 percent discount to a total of 100?

    Interview preparation

    Say your answer out loud first, then open the model answer. Interviewers care more about your reasoning than the exact words.

    Beginner How do you generate unit tests with Copilot?

    Model answer

    I select the function and type /tests in Copilot Chat, adding the edge cases I want, like "unknown code, no code, zero total". Copilot writes tests in the framework the project already uses. Then I read each one and run them.

    Interviewer follows up

    What if the project has no test framework yet?

    You

    Copilot can suggest one and the setup, but I'd decide which framework the team should use and tell it, rather than accept whatever it picks.

    Intermediate What makes a generated test good or weak?

    Model answer

    A good test checks one behaviour with an exact expected value, like expect applyDiscount(100, 'NOPE') to equal 100. A weak one only checks that the result is defined or doesn't throw, so it passes even when the logic is wrong. I also check the test name says the behaviour.

    Experienced developer Copilot generated ten tests and two fail. Do you delete the failing ones?

    Model answer

    No, those two are the interesting ones. I read the assertion and the code. If the code is wrong, like returning NaN for an unknown discount code, I fix the code and keep the test. If the test assumed behaviour we don't want, I fix the test. Deleting it throws away the bug report.

    Scenario Unit tests pass, but the checkout API still returns the wrong total in staging. What test is missing?

    Model answer

    An integration test. Each unit works alone, but something between them is wrong, maybe the route passes the code in a different field. I'd ask Copilot for a supertest test that posts a real cart to POST /cart/total and checks the status and total, with the server started and stopped in setup and teardown.

    Quick revision

    Key points

    • /tests on a selection generates tests in the project's framework; agent mode can also write and run them.
    • Unit tests check one function in isolation; integration tests check parts working together.
    • Name edge cases in the prompt and ask Copilot for the ones you missed.
    • Strong assertions: one behaviour, exact expected value. Weak: only 'is defined'.
    • A failing generated test means a bug in the code or in the test. Decide which, don't just delete it.
    • Tests from Copilot are code you review; a passing test can still check the wrong thing.

    Important terminology

    Unit test
    A test that checks one small piece of code, such as a single function, in isolation from databases, networks and other modules.
    Integration test
    A test that checks several parts working together, for example an HTTP route, the business logic and the JSON response.
    Edge case
    An input at or beyond the normal range, such as empty, missing, zero, negative, very large or invalid values.
    Assertion
    The line in a test that compares the actual result with the expected one and fails the test if they differ.
    /tests
    A Copilot Chat slash command that generates tests for the selected code.
    Arrange, act, assert
    A common test layout - set up the inputs, call the code, then check the result.

    Common mistakes

    • Accepting tests with weak assertions that can never fail.
    • Deleting failing generated tests instead of investigating them.
    • Calling a test that hits a real database and API a unit test.

    Exam tips

    • "Generate tests for selected code" = /tests.
    • "Make sure tests cover unusual inputs" = ask Copilot to identify edge cases.
    • "Verify the API and the business logic work together" = integration test.

    Five quick revision questions

    1. 1.Which slash command generates tests?Show

      /tests

    2. 2.What does a unit test isolate?Show

      One small piece of code, such as a single function.

    3. 3.Give two edge cases for applyDiscount(total, code).Show

      An unknown code and no code (also a zero or very large total).

    4. 4.What makes an assertion strong?Show

      It checks one behaviour against an exact expected value.

    5. 5.A generated test fails. What are the two possibilities?Show

      The code has a bug, or the test is wrong.

    Official references

    Finished this lesson? Tick it off. Your progress is saved in this browser.

    Next up: Security Improvements and Performance Fixes

    Studying with a friend? Send them this lesson

    It's free and needs no sign-up. Their progress saves in their own browser.

    Lesson done? Make it stick with a quick gameSort It, Match the Pairs, Lightning Round and Who Am I? Earn XP and badges. Play ❯

    Install MSDEVBUILD Azure

    Free · no account · works offline

    Save the whole course for offline ›

    Hi, I’m your Nimbus

    Your study buddy. Pick what we do next.

    MSDEVBUILD · Multi-Stack Dev Build

    Sign in to MSDEVBUILD

    One account for Azure certifications and the blog: sign in here and you are signed in on both. Your XP, streak, practice deck and certificate stay in sync on every device. Optional: everything works without an account.