Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

To unit test a Python class, create a real instance, call one public behavior, and assert an observable result: a return value, a state change, or a documented exception. Python’s built-in unittest provides a standard-library structure for doing this; pytest can also run unittest tests and offers a different style when you want fixtures and parametrization.

Start with behavior, not implementation

A useful unit test describes what a class promises to do, rather than how its internals happen to do it. Construct the class under test, exercise its public interface, then check the result. Avoid mocking the class itself or asserting that a private helper was called: those checks can keep passing even when the class’s observable behavior is wrong.

For example, suppose an Account accepts an initial balance and its deposit() method updates that balance. A minimal unittest test could look like this:

import unittest
from account import Account


class AccountTests(unittest.TestCase):
    def test_deposit_updates_balance(self):
        account = Account(balance=10)

        account.deposit(5)

        self.assertEqual(account.balance, 15)

This example assumes that the class has those constructor and method names and exposes its balance. Adapt the names and expected result to the real class contract. The test passes only if the observable balance is 15 after the deposit.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Elebase USB to USB C Adapter for iPhone 18 Pro Max,USBC Car Charger Adapter
  • Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
  • Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
  • Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
  • Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
  • 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.

Organize tests with unittest

unittest is included with Python. A test case is a subclass of unittest.TestCase; each test method begins with test, and assertions such as assertEqual make the expected outcome explicit. The Python unittest documentation recommends self-contained tests that can run on their own or alongside other cases.

Run a test module directly with Python:

python -m unittest test_account.py

To let unittest discover tests in a project, use:

python -m unittest discover

These are command-line entry points; discovery details and conventions can vary by Python version and project layout. The current Python documentation describes Python 3.14 behavior, so consult the documentation for the Python version your project supports before relying on version-specific discovery behavior.

Keep test state independent

A test should not depend on another test having run first, or leave shared state that changes another test’s result. Python creates a new TestCase instance for each test method. If several methods need the same kind of starting state, setUp() can create a fresh object before each method:

Rank #2
Anker USB-C Hub, 5-in-1 USB Hub for Laptops, 4K HDMI Multiport Adapter
  • 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
  • 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
  • Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
  • 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
  • What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.
class AccountTests(unittest.TestCase):
    def setUp(self):
        self.account = Account(balance=10)

    def test_deposit_updates_balance(self):
        self.account.deposit(5)
        self.assertEqual(self.account.balance, 15)

    def test_withdrawal_updates_balance(self):
        self.account.withdraw(3)
        self.assertEqual(self.account.balance, 7)

Use tearDown() to release resources created for a test, such as an open file or temporary service. It runs after the test method when setup succeeded, including when the test fails. For ordinary in-memory objects, cleanup is often unnecessary.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

setUpClass() and tearDownClass() can manage a resource shared across methods, but shared fixtures can undermine isolation and complicate parallel execution. The Python documentation cautions that shared fixtures “do not play well with [potential] features like test parallelization and they break test isolation. They should be used with care.” Prefer a fresh per-test object unless there is a concrete reason to share a resource.

Choose cases that match the class contract

Do not try to test every imaginable input. Choose cases that verify meaningful promises made by the class, with each test focused on a behavior and a clear expected result.

Rank #3
Sale
Anker USB C Hub, 7in1 Multi-Port USB Adapter, 4K@60Hz USBC to HDMI Splitter
  • Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
  • Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
  • Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
  • Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
  • What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.
  • Normal behavior: Check the ordinary input and expected return value or state change.
  • Boundaries and defaults: Check empty, minimum, maximum, or default values when they matter to the contract.
  • Invalid input: Verify the documented exception for an unsupported argument or state.
  • State transitions: Check that a later operation behaves correctly after an earlier one changes the object.
  • Collaborator behavior: Verify an external interaction only when that interaction is part of the class’s promised behavior or needs isolation.

For invalid input, unittest can check for an exception with assertRaises:

def test_negative_deposit_is_rejected(self):
    account = Account(balance=10)

    with self.assertRaises(ValueError):
        account.deposit(-1)

Use the exception type and input expected by the actual class. If the contract specifies a particular error message, test it only when that message is meaningful to callers.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

For several related inputs, subTest() can report which case failed while allowing the remaining cases to run:

Rank #4
Sale
UGREEN USB to USB C Adapter Combo 4-Pack, 10Gbps USB C Converter Space Gray
  • Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
  • Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
  • Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
  • Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
  • Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft
def test_rejects_invalid_deposits(self):
    account = Account(balance=10)

    for amount in (-1, 0):
        with self.subTest(amount=amount):
            with self.assertRaises(ValueError):
                account.deposit(amount)

Use such a loop only if each input shares the same expected behavior; separate test methods are clearer when outcomes differ.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Mock external collaborators selectively

For a pure method operating only on its arguments and object state, a real class instance is usually clearer than a mock. A fake or mock can help isolate a network client, clock, filesystem, database, or other boundary when using the real dependency would make a unit test slow, costly, or nondeterministic.

Python’s standard library includes unittest.mock. A mock can provide configured return values or side effects and record calls; patch() temporarily replaces a name and restores it when its scope ends. Patch the name in the namespace where the code under test looks it up, not automatically the module where the dependency was originally defined. The unittest.mock documentation explains patching and options such as autospec and create_autospec(), which can constrain a mock to an object’s attributes and call signature.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Best Value
Anker USB C Hub, 5-in-1 USBC to HDMI Splitter with 4K Display
  • 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
  • Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
  • Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
  • HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
  • What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.

A recorded call proves that an interaction occurred; it does not, on its own, prove that your class produced the right result for its caller. Keep an assertion about the class’s observable behavior as the main check.

Choose unittest or pytest for the way you work

unittest is available with Python and structures tests as TestCase methods with self.assert* assertions. Pytest is a separate framework that uses plain functions and Python’s assert syntax, and provides fixture injection and parametrization in its own test style.

Consideration unittest pytest
Availability Included in Python’s standard library. Separate framework; install it for the project.
Typical test style TestCase subclass, test_* method, and self.assert*. Test function and plain assert.
Setup setUp() and tearDown() methods; shared class fixtures are available. Fixtures can be injected into plain test functions.
Parametrization subTest() is available for related cases. Parametrization is available in pytest-style tests, but not for unittest.TestCase methods.
Using an existing suite Runs with unittest’s test runner. Can collect and run unittest tests in test_*.py and *_test.py files.

According to pytest’s unittest integration guide, pytest supports unittest features including setup, teardown, and subtests. However, pytest fixtures normally cannot be passed as arguments to TestCase methods, and pytest parametrization does not work in those subclasses. Some other pytest features are likewise unavailable there. You can use pytest as a runner for an existing unittest suite, then move tests to plain functions if you want its full fixture and parametrization features.

A practical workflow for a new class

  1. Write down the public behavior and the result a caller should observe.
  2. Create a real instance with a known initial state.
  3. Call one behavior through the class’s public interface.
  4. Assert the return value, resulting state, or documented exception.
  5. Add boundary or transition cases where the contract makes them important.
  6. Introduce a fake or mock only to isolate an external collaborator or verify a meaningful interaction.
  7. Run the test alone and with the suite to catch hidden state dependencies.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.