Skip to content

Unit testing in C#, JavaScript and Python, plus mocks

A unit test checks one small piece of behavior (a function, a class, a pricing rule) in isolation, in milliseconds, with no network, database or clock outside its control. A healthy suite runs thousands of them on every commit, so a broken rule is caught minutes after it is written instead of in production. The ideas are the same in every language: arrange the inputs, act by calling the code, assert on the observable result, and run many cases through one test with parameterized data.

This page shows those ideas in the three ecosystems this site covers, using one invented OrdersPortal domain (pricing, carts and shipping), and then covers test doubles: how to replace dependencies such as an email sender or the system clock. Every sample was run: the C# tests with xUnit v3 4.0.3 on .NET SDK 10.0.115, the TypeScript tests with Vitest 5.1.1 on Node.js 22, and the Python tests with pytest 9.2.0 on Python 3.14.

Topic Framework Highlights
Unit testing with xUnit xUnit v3 (also NUnit, MSTest) [Fact], [Theory], Microsoft.Testing.Platform in .NET 10
Unit testing with Vitest Vitest (also Jest, node:test) describe/it, it.each, async assertions, vi.fn()
Unit testing with pytest pytest Fixtures, parametrize, pytest.raises
Mocking and test doubles Moq, FakeTimeProvider, vi.fn, unittest.mock Stubs, mocks, fakes and spies, and when not to use them

For the bigger picture (the test pyramid, coverage and principles) read the testing overview; for tests that cross process boundaries read integration and end-to-end testing.

.NET has three mature frameworks: xUnit (the most common for new projects, and what the ASP.NET Core team uses), NUnit and MSTest. They differ mostly in attribute names ([Fact] and [Theory] versus [Test] and [TestCase] versus [TestMethod] and [DataRow]). xUnit creates a new instance of the test class for every test, so the constructor is the per-test setup and IDisposable or IAsyncLifetime is the teardown; shared expensive setup goes in a class fixture.

xUnit v3 test projects are executables (<OutputType>Exe</OutputType>) that run on Microsoft.Testing.Platform (MTP). With the .NET 10 SDK, dotnet test must be told to use MTP through global.json; otherwise it fails with “Testing with VSTest target is no longer supported”. Use Assert.Equal(expected, actual) with the expected value first so failure messages read correctly. FluentAssertions 8 moved to a commercial license (Xceed) for commercial use; Shouldly or AwesomeAssertions are open-source alternatives if you want fluent syntax.

global.json at the repository root:

{ "test": { "runner": "Microsoft.Testing.Platform" } }

OrdersPortal.Tests.csproj:

<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<OutputType>Exe</OutputType>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="xunit.v3" Version="4.0.3" />
<PackageReference Include="Moq" Version="4.21.0" />
<PackageReference Include="Microsoft.Extensions.TimeProvider.Testing" Version="10.11.0" />
</ItemGroup>
</Project>

OrderPricingTests.cs (the code under test is included so the sample is complete):

using Xunit;
// Code under test (normally in the OrdersPortal project).
public static class OrderPricing
{
public static decimal Total(decimal subtotal, int loyaltyPoints)
{
ArgumentOutOfRangeException.ThrowIfNegative(subtotal);
var discount = loyaltyPoints >= 1000 ? 0.10m : loyaltyPoints >= 500 ? 0.05m : 0m;
var shipping = subtotal >= 50m ? 0m : 4.99m;
return Math.Round(subtotal * (1 - discount) + shipping, 2);
}
}
public class OrderPricingTests
{
[Fact]
public void Total_AddsShipping_BelowFreeShippingThreshold()
{
// Arrange
var subtotal = 20.00m;
// Act
var total = OrderPricing.Total(subtotal, loyaltyPoints: 0);
// Assert
Assert.Equal(24.99m, total);
}
[Theory]
[InlineData(100.00, 0, 100.00)] // no discount, free shipping
[InlineData(100.00, 500, 95.00)] // 5% at 500 points
[InlineData(100.00, 1000, 90.00)] // 10% at 1000 points
[InlineData(49.99, 1000, 49.98)] // discount, then shipping below 50
public void Total_AppliesLoyaltyDiscount(decimal subtotal, int points, decimal expected) =>
Assert.Equal(expected, OrderPricing.Total(subtotal, points));
[Fact]
public void Total_RejectsNegativeSubtotal() =>
Assert.Throws<ArgumentOutOfRangeException>(() => OrderPricing.Total(-1m, 0));
}

Run dotnet test. Output (with the mocking tests from the last section in the same project):

Test run summary: Passed!
total: 8
failed: 0
succeeded: 8
skipped: 0

Pitfalls:

  • [InlineData] with decimal. Attributes cannot hold decimal constants, so the values are written as double literals and converted; for exact money values with many digits, use [MemberData] or TheoryData<decimal, ...> instead.
  • Static state between tests. Tests run in parallel across classes by default, so shared static fields cause random failures. Keep state per test instance.
  • Testing private methods. Test through the public API; a private method that needs its own tests is usually a class waiting to be extracted.

Vitest and Jest share almost the same API (describe, it/test, expect, beforeEach). Vitest runs TypeScript and ES modules natively through Vite’s transform pipeline, so it needs no Babel or ts-jest setup and is the default for Vite, Vue, Svelte and many React projects; Jest remains widespread, especially in older React and Node.js code bases. Node.js also ships a built-in runner (node --test) for libraries that want zero dependencies.

Return or await every promise in a test: with await expect(promise).resolves... and .rejects... the runner waits for the result, while a forgotten await lets the test pass before the assertion runs. it.each runs one test body over a table of cases. For floating-point money values, compare with toBeCloseTo, or better, keep amounts in integer cents in production code.

Save the two files under src/, add "type": "module" to package.json, then run npm install -D vitest@5.1.1 and npx vitest run. src/cart.ts:

export interface CartLine { sku: string; unitPrice: number; quantity: number }
export function cartTotal(lines: CartLine[], couponPercent = 0): number {
if (couponPercent < 0 || couponPercent > 50) throw new RangeError('Coupon must be between 0 and 50%');
const subtotal = lines.reduce((sum, l) => sum + l.unitPrice * l.quantity, 0);
return Math.round(subtotal * (100 - couponPercent)) / 100;
}
export async function loadCart(fetchCart: (id: string) => Promise<CartLine[]>, id: string): Promise<number> {
const lines = await fetchCart(id);
return cartTotal(lines);
}

src/cart.test.ts:

import { describe, expect, it, vi } from 'vitest';
import { cartTotal, loadCart, type CartLine } from './cart';
const lines: CartLine[] = [
{ sku: 'KB-101', unitPrice: 49.99, quantity: 2 },
{ sku: 'CBL-USB-C', unitPrice: 9.5, quantity: 3 },
];
describe('cartTotal', () => {
it('sums line totals', () => {
expect(cartTotal(lines)).toBe(128.48);
});
it.each([
[0, 128.48],
[10, 115.63],
[50, 64.24],
])('applies a %i%% coupon', (coupon, expected) => {
expect(cartTotal(lines, coupon)).toBeCloseTo(expected, 2);
});
it('rejects coupons above 50%', () => {
expect(() => cartTotal(lines, 60)).toThrow(RangeError);
});
});
describe('loadCart', () => {
it('totals the lines returned by the API', async () => {
const fetchCart = vi.fn().mockResolvedValue(lines);
await expect(loadCart(fetchCart, 'cart-7')).resolves.toBe(128.48);
expect(fetchCart).toHaveBeenCalledWith('cart-7');
});
it('propagates API failures', async () => {
const fetchCart = vi.fn().mockRejectedValue(new Error('503 Service Unavailable'));
await expect(loadCart(fetchCart, 'cart-7')).rejects.toThrow('503');
});
});

Output:

Test Files 1 passed (1)
Tests 7 passed (7)

Pitfalls:

  • Missing await on async assertions. expect(p).rejects.toThrow() without await never fails the test.
  • Mocks leaking between tests. Call vi.restoreAllMocks() (or set restoreMocks: true in the config) so one test’s mock implementation does not affect the next.
  • jsdom for everything. Use the node environment for pure logic; reserve jsdom or happy-dom for code that touches the DOM, since it is slower.

pytest is the de facto standard: tests are plain functions whose names start with test_, and assertions are plain assert statements that pytest rewrites to show both sides on failure. Fixtures are functions decorated with @pytest.fixture that tests request by naming them as parameters; they replace setup methods, can depend on other fixtures, can clean up after a yield, and can be scoped per function, module or session. @pytest.mark.parametrize runs a test once per row of data, and each row is reported separately. pytest.raises asserts that an exception, optionally with a matching message, is raised.

Built-in fixtures cover common needs: tmp_path for a temporary directory, monkeypatch to set environment variables or attributes, and capsys to capture output. The standard library’s unittest still works and pytest runs unittest-style tests too. In this sample, the third parameter row failed on the first run because Decimal.quantize rounds half to even by default (0.125 became 0.12); the fix in the code under test was rounding=ROUND_HALF_UP, which is exactly the kind of bug parameterized tests catch.

Layout: ordersportal/__init__.py (empty), ordersportal/shipping.py and tests/test_shipping.py. Run python -m pytest -v (or uv run --with pytest pytest -v). ordersportal/shipping.py:

from dataclasses import dataclass
from decimal import ROUND_HALF_UP, Decimal
@dataclass(frozen=True)
class Parcel:
weight_kg: Decimal
express: bool = False
class RateTable:
"""Loads carrier rates; slow in production, so tests pass in a small table."""
def __init__(self, per_kg: dict[str, Decimal]):
self._per_kg = per_kg
def per_kg(self, service: str) -> Decimal:
return self._per_kg[service]
def shipping_cost(parcel: Parcel, rates: RateTable) -> Decimal:
if parcel.weight_kg <= 0:
raise ValueError("weight must be positive")
service = "express" if parcel.express else "standard"
base = Decimal("5.00") if parcel.express else Decimal("0.00")
return (base + parcel.weight_kg * rates.per_kg(service)).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)

tests/test_shipping.py:

from decimal import Decimal
import pytest
from ordersportal.shipping import Parcel, RateTable, shipping_cost
@pytest.fixture
def rates() -> RateTable:
return RateTable({"standard": Decimal("0.50"), "express": Decimal("1.50")})
@pytest.mark.parametrize(
("weight", "express", "expected"),
[
("4", False, "2.00"),
("4", True, "11.00"),
("0.25", False, "0.13"), # 0.125 rounds half up, not to even
],
)
def test_shipping_cost(rates, weight, express, expected):
assert shipping_cost(Parcel(Decimal(weight), express), rates) == Decimal(expected)
def test_rejects_non_positive_weight(rates):
with pytest.raises(ValueError, match="weight must be positive"):
shipping_cost(Parcel(Decimal("0")), rates)

Output:

tests/test_shipping.py::test_shipping_cost[4-False-2.00] PASSED [ 25%]
tests/test_shipping.py::test_shipping_cost[4-True-11.00] PASSED [ 50%]
tests/test_shipping.py::test_shipping_cost[0.25-False-0.13] PASSED [ 75%]
tests/test_shipping.py::test_rejects_non_positive_weight PASSED [100%]
============================== 4 passed in 0.03s ===============================

Pitfalls:

  • Floats for money. 0.1 + 0.2 != 0.3; use Decimal and an explicit rounding mode, and compare floats only with pytest.approx.
  • Session-scoped fixtures with mutable state. A fixture shared across tests that one test modifies makes results depend on test order. Keep mutable fixtures function-scoped.
  • Import path confusion. Run pytest as python -m pytest from the project root (or configure pythonpath in pyproject.toml) so ordersportal imports the same way in every environment.

A test double stands in for a real dependency the unit under test uses. Gerard Meszaros’s names are still the clearest: a dummy is passed but never used; a stub returns canned answers; a mock records calls so the test can verify them; a spy wraps a real object and records calls; a fake is a working lightweight implementation (an in-memory store, a controllable clock). Libraries blur the terms: a Moq Mock<T> acts as a stub when you only Setup it and as a mock when you Verify it.

Replace dependencies that are slow, non-deterministic or have side effects: databases, HTTP APIs, email and SMS, the clock, random numbers. In .NET, depend on TimeProvider (built in since .NET 8) instead of DateTime.UtcNow, and use FakeTimeProvider from Microsoft.Extensions.TimeProvider.Testing to move time in tests. Do not mock value objects, pure functions or the class under test. Verify interactions only when the interaction is the behavior (an email must be sent exactly once); otherwise assert on returned values or state. Equivalent tools: vi.fn() and vi.useFakeTimers() in Vitest, jest.fn() in Jest, and unittest.mock or pytest-mock’s mocker in Python. Moq is the most used .NET mocking library; NSubstitute and FakeItEasy are popular alternatives.

ReminderServiceTests.cs (same project as the xUnit section):

using Microsoft.Extensions.Time.Testing;
using Moq;
using Xunit;
// Code under test: depends on abstractions for the clock, the data and the email sender.
public sealed record Invoice(int Id, string CustomerEmail, DateTimeOffset DueDate, bool Paid);
public interface IInvoiceStore { Task<IReadOnlyList<Invoice>> GetOpenAsync(); }
public interface IEmailSender { Task SendAsync(string to, string subject); }
public sealed class ReminderService(IInvoiceStore store, IEmailSender email, TimeProvider clock)
{
public async Task<int> SendOverdueRemindersAsync()
{
var now = clock.GetUtcNow();
var overdue = (await store.GetOpenAsync()).Where(i => !i.Paid && now - i.DueDate > TimeSpan.FromDays(14)).ToList();
foreach (var invoice in overdue)
await email.SendAsync(invoice.CustomerEmail, $"Invoice {invoice.Id} is overdue");
return overdue.Count;
}
}
public class ReminderServiceTests
{
private static readonly DateTimeOffset Today = new(2026, 11, 18, 9, 0, 0, TimeSpan.Zero);
[Fact]
public async Task Sends_one_reminder_per_invoice_more_than_14_days_overdue()
{
// Stub: returns canned data, never verified.
var store = new Mock<IInvoiceStore>();
store.Setup(s => s.GetOpenAsync()).ReturnsAsync(
[
new Invoice(1, "dana@example.test", Today.AddDays(-20), Paid: false), // overdue
new Invoice(2, "lee@example.test", Today.AddDays(-3), Paid: false), // not yet
new Invoice(3, "sam@example.test", Today.AddDays(-30), Paid: true), // paid
]);
// Mock: we verify how it was called.
var email = new Mock<IEmailSender>();
// Fake: a working, controllable clock from Microsoft.Extensions.TimeProvider.Testing.
var clock = new FakeTimeProvider(Today);
var sent = await new ReminderService(store.Object, email.Object, clock).SendOverdueRemindersAsync();
Assert.Equal(1, sent);
email.Verify(e => e.SendAsync("dana@example.test", "Invoice 1 is overdue"), Times.Once);
email.VerifyNoOtherCalls();
}
[Fact]
public async Task Invoice_becomes_overdue_when_the_clock_moves_past_14_days()
{
var store = new Mock<IInvoiceStore>();
store.Setup(s => s.GetOpenAsync()).ReturnsAsync([new Invoice(2, "lee@example.test", Today.AddDays(-3), Paid: false)]);
var email = new Mock<IEmailSender>();
var clock = new FakeTimeProvider(Today);
var service = new ReminderService(store.Object, email.Object, clock);
Assert.Equal(0, await service.SendOverdueRemindersAsync());
clock.Advance(TimeSpan.FromDays(12)); // now 15 days past due
Assert.Equal(1, await service.SendOverdueRemindersAsync());
}
}

Both tests pass as part of the eight shown in the xUnit section.

Pitfalls:

  • Over-mocking. Tests that set up five mocks and verify every call break on every refactor while behavior is unchanged. Prefer fakes and state assertions; mock only at the boundaries you own (your IEmailSender, not the SMTP library).
  • Mocking types you do not own. Mocking HttpClient internals or EF Core DbSet reproduces their behavior badly. Wrap them behind your own interface, or test them with integration tests.
  • Hidden time and randomness. Code that reads DateTime.Now or Random.Shared directly cannot be tested deterministically; inject TimeProvider or a seedable source.
You are testing Use
.NET libraries and services xUnit v3 (or NUnit/MSTest if the team already uses it), Moq or NSubstitute, FakeTimeProvider
TypeScript in a Vite-based front end or a modern Node.js service Vitest
An existing Jest code base Jest; migrate to Vitest only if speed or ESM support hurts
Python code pytest, with pytest-mock for mocks
Code with a slow or external dependency A fake when the dependency has behavior; a stub for canned answers; a mock only to verify a required call

What makes a good unit test? It is fast, isolated, repeatable and self-validating; it tests one behavior through the public API, has a name that states the scenario and expected result, and fails for exactly one reason. It survives refactoring because it checks outcomes, not implementation details.

What is the difference between a stub, a mock and a fake? A stub returns canned data and is not verified; a mock records interactions so the test can assert on them; a fake is a working simplified implementation such as an in-memory repository or FakeTimeProvider.

Why does xUnit create a new test class instance per test? To isolate tests: state set in one test cannot leak into another. Setup goes in the constructor, cleanup in Dispose, and expensive shared setup in class or collection fixtures.

How do you test code that depends on the current time? Inject TimeProvider (.NET 8+) or a clock interface, and in tests use a fake you can set and advance; in JavaScript use vi.useFakeTimers() and vi.setSystemTime(); in Python inject a clock function or patch it with monkeypatch.

Senior scenario: OrdersPortal’s 4,000 unit tests take 12 minutes and fail randomly a few times a week. How do you fix the suite? Measure first: find the slowest tests and the flaky ones from CI history. Slow “unit” tests usually touch real I/O (files, databases, Task.Delay); move those to the integration layer or replace the dependency with a fake and a fake clock. Flakiness usually comes from shared static state, test order, real time, or parallel tests touching the same resource; make state per-test, inject time, and isolate shared resources. Quarantine known flaky tests with an owner and a deadline instead of retrying blindly, run the suite in parallel, and add a CI budget so the problem does not return.