How to Write Test Cases in Odoo?

blog-banner

Quality assurance is highly important for any modern ERP system. Odoo's modular architecture and powerful ORM have brought along a built-in testing framework, which a developer shouldn't look past. Unit tests are test cases to check the smallest pieces of your code - an isolated, individual function, method, or model - to each part behaves exactly as expected before its inclusion with the rest of the system.

Importance of Unit Testing in Odoo

Unit tests should be considered less of an "activity," but instead an investment that will yield huge dividends over the lifetime of your development.

Here it is with a clean structure and no strong tags:

  • Quality and Reliability: Tests verify that your module’s business logic works as intended, covering calculations, state transitions and constraints. They also help prevent unnoticed bugs.
  • Regression Protection: Tests act as a safety net during refactoring or version upgrades, showing whether any functionality was broken.
  • Living Documentation: Good tests illustrate how a function should be used and what output it should produce, along with helpful log messages.
  • Safe Refactoring: Developers can improve or reorganize code confidently because tests catch anything that alters existing behavior.
  • Support for Agile Development: Automated tests make fast iteration and continuous integration easier by streamlining verification.

How Odoo Builds on Python’s unit test Framework

Odoo's test infrastructure is based on Python's standard unit test library extended by classes and helpers that are particularly fit for the Odoo context.

Step 1: Prerequisites for Testing Environment Setup

Before running any test, make sure that your Odoo server has started with the testing enabled and if you didn't enable flag then your test cases didn't work properly.

You can do this directly from the command line by including the --test-enable flag when launching Odoo. If I have setup in code editor also added this flag to your editor.

Example command (bash):

 
    ./odoo-bin -c /etc/odoo/odoo.conf -d my_test_db -i my_module --test-enable 
  

Explanation:

  • -c → Path to your Odoo configuration file
  • -d → Name of the temporary test database (Odoo creates and drops it automatically)
  • -i → The module to install and test
  • --test-enable → Enables the test framework so Odoo will detect and execute test classes

Step 2: Prepare the folder structure for unit test cases

In your custom module, create folder tests.

Every test file name should begin with “test_” so that Odoo can automatically detect and run it when the all-test cases are run.

Example structure:

 
    // my_module/ 
├── __init__.py 
├── __manifest__.py 
├── models/ 
│   └── res_partner.py 
└── tests/ 
    ├── __init__.py 
    └── test_core.py
  

Make sure to import all your test files inside tests/__init__.py:

from. import test_core

Step 3: Example Code

models/res_partner.py

 
   from odoo import models, fields, api 
 
class ResPartner(models.Model): 
    _inherit = 'res.partner' 
 
    credit_limit = fields.Float(default=0.0) 
 
    @api.model 
    def create(self, vals): 
         
        if vals.get('is_company'): 
            vals['credit_limit'] = 50000 
        else: 
            vals['credit_limit'] = 5000 
        return super().create(vals) 
  

tests/test_core.py

 
   from odoo.tests.common import TransactionCase 
 
class TestPartnerCredit(TransactionCase): 
 
    def test_credit_limit_for_company(self): 
        """Company partners should get a 50,000 credit limit""" 
        partner = self.env['res.partner'].create({ 
            'name': 'Test Company', 
            'is_company': True 
        }) 
        self.assertEqual(partner.credit_limit, 50000) 
 
    def test_credit_limit_for_individual(self): 
        """Individual partners should get a 5,000 credit limit""" 
        partner = self.env['res.partner'].create({ 
            'name': 'Test Person', 
            'is_company': False 
        }) 
        self.assertEqual(partner.credit_limit, 5000)
  

Step 4: Trigger test failure (for demonstration)

An error should be introduced into your model logic by you to confirm that your test cases are running as expected.

For example - the rule in res_partner.py should be modified as below:

if vals.get('is_company'):
vals['credit_limit'] = 10000 # Intentional mistake

Now your test command should be rerun, and a failure message should be shown in terminal:

AssertionError: 10000.0! = 50000.0

this output is confirmed by the fact that:

The test was run successfully.


The mismatch in expected logic was correctly detected by the validation.

Basic Value Assertions

  • assertEqual(a, b) → It ascertains whether a and b hold the same value.
  • assertNotEqual(a, b) → it means 'a' and 'b' do not hold the same value.
  • assertTrue(x) → It is passed if x evaluates True.
  • assertFalse(x) → It is passed if x evaluates too False.

Object Identity Checks

  • assertIs(a, b) → Returns true if a and b refer exactly hold same object in memory.
  • assertIsNot(a, b) → It is passed if a and b do not hold the same object.
  • assertIsNone(x) → The test passes when x is None.
  • assertIsNotNone(x) → The test will pass when x is anything but None.

Collection Membership

  • assertIn(a, b) →The test confirms that element exists within collection b.
  • assertNotIn(a, b) → The test ensures that value is not in collection b.
  • assertCountEqual(a, b) → The assertion checks that lists a and b contain the same elements, regardless of order.

Handling Exceptions

  • assertIn(a, b) →The test confirms that element exists within collection b.
  • assertNotIn(a, b) → The test ensures that value is not in collection b.
  • assertCountEqual(a, b) → The assertion checks that lists a and b contain the same elements, regardless of order.
  • assertRaises(Error, func, *args) → It is checked that calling func(args) triggers the expected Error.

Odoo consultant

Wrapping up

Unit testing within Odoo is not just a recognized best practice but also the foundation of building stable, maintainable, and high-quality modules in the Odoo ERP framework. Developers using the built-in testing framework of Odoo can validate business logic early and avoid regressions later, making version upgrades smooth and reliable.

Consistent usage of the testing framework can serve as a safety net and also as a type of progressive documentation that team members and other developers can get accustomed to and depend on. Whether you are developing a mere customization or a complicated enterprise module, you will be glad that you wrote unit tests because they will save you from spending hours debugging and reworking on your customization module.

Contact us

For Your Business Requirements

Text to Identify Refresh CAPTCHA