PHPUnit Tests for Bitrix Modules: Bootstrap to CI/CD

Our company is engaged in the development, support and maintenance of Bitrix and Bitrix24 solutions of any complexity. From simple one-page sites to complex online stores, CRM systems with 1C and telephony integration. The experience of developers is confirmed by certificates from the vendor.
Showing 1 of 1All 1626 services
PHPUnit Tests for Bitrix Modules: Bootstrap to CI/CD
Simple
~1 day
Frequently Asked Questions

Our competencies:

Development stages

Latest works

  • image_website-b2b-advance_0.webp
    B2B ADVANCE company website development
    1356
  • image_bitrix-bitrix-24-1c_fixper_448_0.webp
    Website development for FIXPER company
    943
  • image_bitrix-bitrix-24-1c_development_of_an_online_appointment_booking_widget_for_a_medical_center_594_0.webp
    Development based on Bitrix, Bitrix24, 1C for the company Development of an Online Appointment Booking Widget for a Medical Center
    693
  • image_bitrix-bitrix-24-1c_mirsanbel_458_0.webp
    Development based on 1C Enterprise for MIRSANBEL
    828
  • image_crm_dolbimby_434_0.webp
    Website development on CRM Bitrix24 for DOLBIMBY
    731
  • image_crm_technotorgcomplex_453_0.webp
    Development based on Bitrix24 for the company TECHNOTORGKOMPLEKS
    1072

We know: a Bitrix module without tests is a black box. You fix one thing and break another. This is especially painful in modules with business logic: discount calculations, external API integrations, order processing. According to our statistics, 60% of regressions can be prevented by automated tests. Manual testing after each change takes 2-3 hours, automated testing takes 2-3 minutes. One missed side effect — and on a live site, prices drop or notifications fail. PHPUnit tests catch such errors in seconds and run 10 times faster than manual checks.

We integrate PHPUnit into Bitrix modules for dozens of projects. Setting up testing for Bitrix modules has its own specifics: the kernel must be loaded, static calls interfere with isolation. We offer a turnkey solution — PHPUnit setup tailored to your module's architecture. Our clients have reduced regression testing time by 70% and the number of errors in releases by 80%.

Why PHPUnit tests in Bitrix?

Manual module testing after each change is slow and unreliable. One missed side effect — and on a live site, prices drop or notifications fail. Automated tests catch such errors in seconds. They run 10 times faster than manual checks and don't miss regressions.

How we do it: a real case

On one project, a discount calculation module worked correctly in rubles, but when switching currency to euros, the discount doubled due to a rounding error. Manual testing didn't reveal the issue because they only tested with rubles. After implementing PHPUnit tests for all currency scenarios, the error was caught in one minute. Now, with every change to the discount logic, a set of 30 tests runs that check edge cases.

Test structure in a Bitrix module

/local/modules/vendor.mymodule/
    lib/
        Services/
            DiscountService.php
            ShippingCalculator.php
        Repository/
            OrderRepository.php
    tests/
        bootstrap.php
        Unit/
            Services/
                DiscountServiceTest.php
                ShippingCalculatorTest.php
        Integration/
            Repository/
                OrderRepositoryTest.php
    phpunit.xml
    composer.json

Environment setup: phpunit.xml and bootstrap

<?xml version="1.0" encoding="UTF-8"?>
<phpunit
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:noNamespaceSchemaLocation="vendor/phpunit/phpunit/phpunit.xsd"
    bootstrap="tests/bootstrap.php"
    cacheDirectory=".phpunit.cache"
    executionOrder="depends,defects"
    requireCoverageMetadata="false"
    beStrictAboutCoverageMetadata="false"
>
    <testsuites>
        <testsuite name="Unit">
            <directory>tests/Unit</directory>
        </testsuite>
        <testsuite name="Integration">
            <directory>tests/Integration</directory>
        </testsuite>
    </testsuites>

    <source>
        <include>
            <directory suffix=".php">lib</directory>
        </include>
    </source>

    <coverage>
        <report>
            <html outputDirectory="tests/_coverage"/>
            <clover outputFile="tests/_coverage/clover.xml"/>
        </report>
    </coverage>
</phpunit>
<?php
// tests/bootstrap.php

$bitrixLoaded = false;

// Unit-тесты без ядра Битрикс — быстро
if (getenv('PHPUNIT_NO_BITRIX') === 'true') {
    require_once __DIR__ . '/../vendor/autoload.php';
    return;
}

// Integration-тесты с ядром Битрикс — медленнее
define('NO_KEEP_STATISTIC', true);
define('NOT_CHECK_PERMISSIONS', true);
define('BX_WITH_ON_AFTER_EPILOG', false);
define('BX_NO_ACCELERATOR_RESET', true);
define('STOP_STATISTICS', true);

$docRoot = realpath(__DIR__ . '/../../../..');
$_SERVER['DOCUMENT_ROOT'] = $docRoot;
$_SERVER['HTTP_HOST']     = 'localhost';
$_SERVER['SERVER_NAME']   = 'localhost';

require_once $docRoot . '/bitrix/modules/main/include/prolog_before.php';
require_once __DIR__ . '/../vendor/autoload.php';

\Bitrix\Main\Loader::includeModule('vendor.mymodule');

Unit test example with isolated business logic

// tests/Unit/Services/DiscountServiceTest.php
namespace Tests\Unit\Services;

use PHPUnit\Framework\TestCase;
use PHPUnit\Framework\MockObject\MockObject;
use Vendor\Mymodule\Services\DiscountService;
use Vendor\Mymodule\Repository\OrderRepositoryInterface;
use Vendor\Mymodule\Repository\UserRepositoryInterface;

class DiscountServiceTest extends TestCase
{
    private DiscountService $service;
    private OrderRepositoryInterface&MockObject $orders;
    private UserRepositoryInterface&MockObject $users;

    protected function setUp(): void
    {
        $this->orders  = $this->createMock(OrderRepositoryInterface::class);
        $this->users   = $this->createMock(UserRepositoryInterface::class);
        $this->service = new DiscountService($this->orders, $this->users);
    }

    public function testNewUserGetsNoDiscount(): void
    {
        $this->orders->method('countCompletedByUser')->willReturn(0);
        $this->users->method('getRegistrationDays')->willReturn(5);

        $discount = $this->service->calculate(userId: 1, orderAmount: 5000.0);

        $this->assertSame(0.0, $discount);
    }

    public function testUserWith5OrdersGets5PercentDiscount(): void
    {
        $this->orders->method('countCompletedByUser')->willReturn(5);
        $this->users->method('getRegistrationDays')->willReturn(180);

        $discount = $this->service->calculate(userId: 1, orderAmount: 5000.0);

        $this->assertSame(250.0, $discount); // 5% от 5000
    }

    public function testDiscountCappedAt20Percent(): void
    {
        $this->orders->method('countCompletedByUser')->willReturn(100);
        $this->users->method('getRegistrationDays')->willReturn(1000);

        $discount = $this->service->calculate(userId: 1, orderAmount: 10000.0);

        $this->assertSame(2000.0, $discount); // 20% — максимум
    }
}

How to speed up and automate tests?

The main technique is separating tests into unit and integration. Unit tests run without the Bitrix kernel in seconds, integration tests with the kernel in minutes. In our bootstrap, the PHPUNIT_NO_BITRIX environment variable is used: if set, tests run without loading the kernel. This allows unit tests to be run on every code change, while integration tests run less frequently, e.g., when merging to the main branch.

# Быстрые unit-тесты без ядра Битрикс (секунды)
PHPUNIT_NO_BITRIX=true vendor/bin/phpunit --testsuite Unit

# Интеграционные тесты с ядром (минуты)
vendor/bin/phpunit --testsuite Integration

# Все тесты с покрытием (требует Xdebug или PCOV)
XDEBUG_MODE=coverage vendor/bin/phpunit --coverage-html tests/_coverage

For CI/CD, we configure runs in GitHub Actions, GitLab CI, or Jenkins. Unit tests execute on every push, integration tests before merging. This provides feedback in 2 minutes. If tests pass, code is automatically deployed to staging. Coverage of key paths reaches 95%, minimizing regression risk.

What's included in the turnkey testing setup

Deliverable Description
Module audit Identify critical areas for testing, assess current architecture
PHPUnit setup Bootstrap, phpunit.xml, environment for unit and integration tests
Test writing Cover key business logic: discounts, cart, integrations
CI/CD integration Add test runs to GitHub Actions, GitLab CI, or Jenkins
Documentation Test descriptions, run and maintenance instructions
Team training How to write new tests and maintain coverage

Estimated timelines

Task Timeline
PHPUnit setup, bootstrap, configuration for the module 4–8 hours
Unit tests for module business logic (≤10 classes) 1–2 days
Integration tests with Bitrix ORM 1–2 days
Module refactoring for testability + 70%+ coverage 3–7 days

Our approach and guarantees

Certified Bitrix specialists. Over 10 years of development experience and 30+ projects with testing implementation. We guarantee that tests will run in your environment and produce stable results. Contact us to discuss setting up tests for your module. Get a consultation — we'll assess your module and propose an implementation plan.

Our approach to solving problems

Each task requires individual analysis and careful planning. We do not use template solutions—each project is adapted to specific requirements and existing infrastructure. Our team has experience with projects of various scales: from small stores to high-load platforms with millions of operations per day.

Guarantees and support

We provide a 12-month warranty on the work performed. During this period, we fix any issues that arise for free. After the project is completed, we provide full documentation and training for your team. Technical support is available for 30 days after launch—we'll help resolve any questions.

Duplicate Products on Page 3: A Bug That Goes to Production

A real case: an online store with pagination through bitrix:catalog.section duplicates products on page three after every second visit. Cache clearing helps for a day, then the duplicates return. Root cause: a custom sort handler collides with PAGEN_1, and under a specific filter combination CIBlockElement::GetList returns identical IDs. Code review missed it; only testing caught it. We build QA for 1C-Bitrix projects that catches such bugs before they hit production: manual functional, automated E2E, load, and acceptance testing. With over a decade of Bitrix experience, we have a library of typical pitfalls and test scenarios that prevent these issues from the start.

How Does a Standard Bitrix Project Break Without Dedicated Testing?

1C-Bitrix is not a landing page. Behind the frontend lie dozens of modules, external integrations, and non‑obvious dependencies. A discount change in sale.discount breaks a promo code in sale.basket.discount — the discount module is one of the most fragile in the platform. Interchange with 1C via catalog.import.1c or REST fails when property mapping is off, resulting in products without price or stock. Core updates — bitrix:main updated, a custom component uses the deprecated CModule::IncludeModule. Without regression testing, every deployment is Russian roulette. Cross‑browser: sale.order.ajax renders differently in Safari and Chrome; the “Place Order” button can move off‑screen on an iPhone. These are not edge cases — they are daily realities for Bitrix teams.

What Does Functional Testing Cover?

We check every business scenario — not just “works or doesn’t work”, but all boundary cases.

Catalog (catalog.section, catalog.element)

  • Smart filter catalog.smart.filter: all property combinations, reset, result counting. Filters by SKUs break most often.
  • Sorting + pagination — the duplicate bug described above.
  • Comparison via catalog.compare.list — add, remove, display differences.
  • Quick view — modal window, cart from modal.

Cart and Order (sale.basket.basket, sale.order.ajax)

  • Adding from catalog, product page, quick order.
  • Discounts: by quantity, by amount, by coupon, cumulative. Discount intersection — at least eight test combinations.
  • Delivery calculation: handlers sale.delivery.services, cost, time, pickup points on map.
  • Payment: sale.paysystem — processing, handling declines, refunds.
  • Order placement: email via main.mail.event, CRM recording, transmission to 1C via sale.export.1c.

Personal Account (sale.personal.section)

  • Registration, authorization, password recovery — including Cyrillic email edge cases.
  • Order history, repeat order.
  • Subscriptions, bonus program.

Forms and Search

  • form.result.new / iblock.element.add.form — submission, validation, file fields.
  • search.page — relevance, morphology, typo handling via search.title.

Why Is Regression Testing Critical for Bitrix?

After every deployment we verify that nothing previously working is broken.

  • Smoke tests — main page loads, catalog shows products, order completes. 5 minutes, run after every deploy. If smoke fails — roll back immediately.
  • Regression suite — 40–80 test cases covering main scenarios before every release.
  • Visual testing — screenshot comparison (Percy or Playwright). A button shifted 20px, font changed after update — test shows the diff.
  • Module checklists — structured lists for sale, catalog, iblock, search. Each module has its own checklist.

What Happens During Load Testing?

The question is not “will the site handle it” but at how many concurrent users catalog.section starts returning 500 errors.

Scenario Share Target Response What Breaks First
Main page 20% < 1 sec Composite cache if not configured
Catalog with filters 30% < 2 sec MySQL – heavy JOINs on b_iblock_element_property
Product page 25% < 1.5 sec Queries for SKUs
Add to cart 10% < 1 sec Table locks on b_sale_basket
Checkout 5% < 3 sec Delivery handlers (external APIs)
Search 10% < 2 sec b_search_content without indexes

Tools:

  • k6 — JavaScript scripting.
  • Apache JMeter — classic, for complex scenarios with cookie authorization.
  • Yandex.Tank — real‑time visualization, integration with Overload.

Output: peak RPS, response times by percentiles p50/p95/p99, bottlenecks (CPU, RAM, MySQL slow queries on b_iblock_element, file cache). Recommendations: which index to add, which query to rewrite with D7 ORM, where to enable composite cache.

What Deliverables Do You Receive After Testing?

  • Test plan with scope, priorities, and quality criteria.
  • Test case suite — functional, regression, load.
  • Defect report in a tracker (Jira/YouTrack) with severity classification.
  • Auto tests (Playwright/Cypress) — basic smoke suite for CI/CD.
  • Load testing protocol with graphs and recommendations.
  • Acceptance certificate after UAT — confirming readiness for launch.

After delivery, we provide free consultation for a month — answering questions on test improvements and process adaptation. Contact us to receive a full package of documents and auto tests.

Cross‑Browser Testing

We test where buyers actually are. Statistics from your Metrica are more important than general market data.

Minimum set:

  • Chrome (last 2 versions) — main traffic.
  • Safari on iOS — critical for mobile checkout, sale.order.ajax often behaves unpredictably.
  • Yandex.Browser — significant share in Russia, Chromium‑based but with extension quirks.
  • Samsung Internet — mobile Android, often forgotten.

Devices:

  • Desktop: 1920×1080, 1366×768.
  • iPhone: 375×812, 390×844 — checkout must be verified.
  • Android: 360×800, 412×915.

Tools: BrowserStack for real devices, Playwright for automation on Chromium/Firefox/WebKit.

Automation

Playwright — primary choice for E2E on Bitrix:

  • Cross‑browser: Chromium, Firefox, WebKit.
  • Parallel execution, automatic waits.
  • Works well with dynamic forms sale.order.ajax.
  • Supports mobile viewports and geolocation.

Cypress:

  • Runs in browser — more stable for SPA‑like interfaces.
  • Excellent visual runner for debugging.
  • Limitation: only Chromium‑based browsers.

PHPUnit for custom code:

  • Unit tests for custom Bitrix components and modules.
  • Tests business logic without frontend dependency.
  • Integration with CI/CD — GitLab CI, GitHub Actions.

UAT – Acceptance Testing

Final check with the client on a staging environment with real data:

  • Jointly compile a list of critical scenarios — 15–20 key customer paths, not 200 test cases.
  • Staging with a copy of the production database (anonymized personal data).
  • Quick bug tracking — Jira/YouTrack, prioritization by severity.
  • Acceptance protocol — document with results, signatures, and launch readiness.

Order UAT support and we guarantee a release without surprises.

QA Process – Integrated, Not Tacked On

  1. Requirements analysis — QA participates in task discussions, catches ambiguities. “Does the discount apply to the product or the order?” — such a question upfront saves two days of debugging.
  2. Test cases before development — scenarios ready before the first line of code.
  3. Code review — checks for typical Bitrix mistakes: uncleared component cache, direct SQL queries instead of ORM, missing $USER‑>IsAuthorized() check.
  4. Functional → regression → deploy.
  5. Post‑release monitoring — errors in bitrix/error.log, metrics in Metrica, alerts for 500 errors.

We have been working with Bitrix for over 10 years and have tested more than 300 projects of various scales — from small online stores to corporate portals with 1C and Bitrix24 integration.

Timelines

Task Duration
Test plan 2–3 days
Functional testing (medium store) 3–5 days
Basic E2E auto test suite (Playwright) 2–3 weeks
Load testing + report 1–2 weeks
Cross‑browser testing 2–3 days
UAT support 3–5 days
QA process from scratch 3–4 weeks

Testing cost is calculated individually for your project. Get a free consultation — we will assess the scope within one business day and provide a preliminary estimate and test plan. Contact us to discuss your project and schedule a call.