MSBA-343 · Lesson 6 of 12 · 19 min

Unit testing with SysTest

▶ Video coming soon A video version of this lesson is on the way.

Every change in the last three clinics had been checked by running a scenario and looking at a trace. That told Prudence the code was faster. It did not tell her the code was still right. When she rewrote the alert queue insert with a notexists join, she had changed which lines received alerts in one edge case: a casting line with a certificate in Waived status. A test caught it before the pull request merged, and that test is where this clinic started.

Prudence had written a handful of SysTest tests in the first clinic series, for the warranty end-date calculation, including the February 29 case that had exposed a bug. Desmond now wanted her to treat tests as part of every change, and to understand the framework well enough to write tests that were fast, isolated and readable by the next developer.

What SysTest is

SysTest is the unit test framework for X++. A test class extends SysTestCase. Each public method whose name starts with test, or that carries the SysTestMethod attribute, is a test. Inside a test, assertion methods such as assertEquals, assertTrue, assertFalse, assertNotNull and assertExpectedInfolog compare what happened with what should have happened. If an assertion fails, the test fails and the framework reports the expected and actual values.

Tests run in Visual Studio's Test Explorer, which lists the tests in the solution, runs one, some or all of them, and shows which passed and which failed with their messages. In the unified developer experience the tests run against the developer's cloud environment, like any other X++ code.

A test for the receipt rule. Helper methods that create the test data are omitted.
[SysTestTarget(classStr(CRInspectionReceiptRule), UtilElementType::Class)]
class CRInspectionReceiptRuleTest extends SysTestCase
{
    [SysTestMethod]
    public void isSatisfied_waivedCertificate_returnsTrue()
    {
        PurchLine line = this.createCastingLine();
        this.createCertificate(line, CRInspectionStatus::Waived);

        boolean result = CRInspectionReceiptRule::construct().isSatisfied(line);

        this.assertTrue(result, 'A waived certificate should satisfy the receipt rule.');
    }
}

Arrange, act, assert

Desmond asked Prudence to write every test in three parts, separated by blank lines. Arrange creates the data and objects the test needs. Act calls the one thing being tested. Assert checks the result. He also asked for test names that say what is tested, under which condition, and what should happen, as in isSatisfied_waivedCertificate_returnsTrue. When a test with that name fails in a build at midnight, whoever reads the log knows what broke without opening the code.

One behaviour per test was the second rule. A test that checks five things stops at the first failure and hides the other four. Five small tests report all five.

Isolation and transactions

A unit test must leave the database as it found it, or the next test may pass or fail for reasons that have nothing to do with the code. SysTest handles this with transaction modes set by the SysTestTransaction attribute on the class. With TestTransactionMode::AutoRollback, the framework runs each test method inside a transaction and rolls it back at the end, so records the test creates never persist. That is the usual choice. Code that itself commits transactions in ways that cannot be nested may need a different mode and explicit cleanup in tearDown.

The framework calls setup and cleanup methods at fixed points. setUpTestCase runs once before all tests in the class, and tearDownTestCase once after. setUp runs before each test, and tearDown after each. Prudence used setUp to create a vendor, an item flagged for inspection and a purchase order header that every test in the class needed, and left anything specific to a test in that test's arrange section.

Company context matters too. A test that creates a purchase line creates it in the current company. Prudence's tests ran in CRCA by default; for the rule that differed in CRMX, she used a changecompany block inside the test so that the test controlled its context explicitly instead of depending on where the developer happened to be logged in.

Test models

Tests belong in their own model. Cobalt Ridge had created CobaltRidgeCustomTests in the first clinic series, referencing CobaltRidgeCustom and the test framework's packages. The production package never contains test code, the build can include or exclude tests, and a developer cannot accidentally call a test helper from production code. The build pipeline in lesson 8 compiles both models but packages only CobaltRidgeCustom; the search pattern for binaries excludes modules whose names end in Tests, which is the convention Microsoft's own pipeline task documentation uses.

Creating test data

Most of the effort in a finance and operations test goes into data. A purchase line needs a vendor, an item, a site and warehouse, a purchase order header, and the setup behind each. Creating them by hand in every test is slow and brittle. Microsoft provides the Acceptance test library, usually called ATL, which gives fluent classes for creating common data and running common processes in tests: creating items, customers and vendors, creating and confirming orders, posting receipts. ATL tests read almost like the business process they describe.

Prudence used ATL for the standard entities and wrote her own small helper class, CRTestData, for Cobalt Ridge's custom fields: flagging an item for inspection, creating a certificate with a given status. Desmond asked her to keep the helper in the test model, to give each method a name that says what it creates, and to avoid any helper that relied on existing data in the environment. A test that passes only because a vendor named V000123 happens to exist in CONFIG will fail in the build.

Where each part of a Cobalt Ridge test lives.
Part of the testWhere it livesExample
Standard data and processesAcceptance test libraryCreate an item, vendor and purchase order; post a product receipt
Custom dataCRTestData helper in CobaltRidgeCustomTestscreateCertificate(line, status); flagForInspection(item)
Shared arrange stepssetUp in the test classVendor, inspected item and purchase order header
The behaviour under testThe test methodisSatisfied for one certificate status

Testing the hardening changes

Each change from the earlier clinics got tests. For the alert queue insert, Prudence wrote one test per certificate status: a line with no certificate should be queued, lines with Received or Waived certificates should not, and a line that does not require inspection should never be queued. The Waived test was the one that failed on her first notexists join, because she had joined only certificates in Received status. The fix was to join on any certificate and filter on status in the join's where clause.

For the global object cache from lesson 5, she wrote a test that built the category map in CRCA, switched to CRUS with changecompany and checked that the map was different. That test would have caught the key bug she had made the week before. For the XDS policy in lesson 2, testing in SysTest was harder, because policies depend on the user's roles. Desmond suggested a SysTest that ran the warranty query under a test user with only the coordinator roles, using the framework's support for running code as another user, and accepting that this test was slower and belonged in a separate test class marked for the nightly run rather than every pull request.

Testing what the user sees

Some behaviour lives in forms. SysTest can test forms through the form adaptor classes that Microsoft generates for standard forms, and through tests generated from Task recorder recordings. In Visual Studio, a developer can import a task recording into the test model, and the tooling generates an X++ test that replays the recorded steps against form adaptors. The generated test is a starting point: Desmond asked Prudence to rename it, remove recorded steps that were incidental, such as opening a filter pane, and add assertions where the recording had only performed actions.

The MB-500 outline mentions creating unit tests by using both SysTest and Task recorder. In practice, Cobalt Ridge used recorded tests sparingly, for a few critical forms, and relied on RSAT for broader business process regression, which lesson 7 covers. The distinction Desmond drew was about who maintains the test. Developers maintain SysTest classes in the test model; functional consultants maintain RSAT test cases in Azure DevOps.

Tests in the build

Tests that only run on one developer's machine are worth little. The build pipeline in lesson 8 compiles the test model, and Cobalt Ridge's build validation for pull requests ran the fast unit tests against a developer environment. The slower tests, such as the XDS test, ran nightly. A failing test blocked the pull request, which meant tests had to be reliable: a test that failed one time in twenty for reasons unrelated to the code was fixed or deleted the same day, because developers learn to ignore tests that cry wolf.

Desmond did not set a coverage target. He asked for tests on every rule that someone could get wrong, every bug that had ever been fixed, and every extension point other developers might rely on, such as the SysExtension category rules from MSBA-341. By the end of the clinic, CobaltRidgeCustomTests had forty-seven tests, and the full set ran in under four minutes.

A testing pyramid. The wide base is SysTest unit tests owned by developers, fast, run on every pull request. The middle is a few Task recorder based form tests and integration tests, run nightly. The narrow top is RSAT business process tests owned by functional consultants, run before releases and service updates.
Many fast unit tests, fewer form and integration tests, and a small set of end-to-end business process tests.

Testing for service updates

Tests earn their keep twice: once when the code is written, and again every time Microsoft ships a service update. A wrapper that compiles after an update can still behave differently if Microsoft has moved logic. Desmond's rule from MSBA-341 was that every Chain of Command wrapper and event handler in CobaltRidgeCustom had at least one test that exercised it through the standard process, not by calling it directly. If an update moved the receipt check so that the wrapper was no longer called, the test that posted a receipt without a certificate and expected an error would fail.

Reading a failure

Prudence's last exercise was to break the code on purpose and read the failure. She changed the receipt rule to treat Waived as unsatisfied, ran the tests and found that two failed: the Waived test, with a message naming the expected and actual values, and an ATL-based test that posted a receipt for a line with a waived certificate and expected no error. The messages pointed straight to the change. Desmond said that was the standard: a failing test should tell you what is wrong without a debugger.

Dependencies and test doubles

Some code is hard to test because it reaches outside itself: it calls an external service, reads the system date or sends an email. A unit test that depends on any of those is slow and fragile. SysTest has no built-in mocking library, so Desmond relied on design instead. Code that needed an outside dependency received it through an interface, and production code passed the real implementation while tests passed a simple fake. The warranty coverage check from MSBA-342, which called the manufacturer's service, used an interface named CRICoverageService. In tests, a fake class returned a fixed answer, so the test could check how the form reacted to covered and not covered pumps without any network call.

The system date was handled the same way. The warranty calculator from the first clinic series took the date as a parameter rather than reading it inside, which is why its February 29 test could run on any day of the year. Prudence found two newer methods that read the date directly and changed them to accept it, so that their tests would not start failing at month-end.

Reviewing tests

Tests are code, and they went through the same pull request review. Desmond's reviewers looked for four things: a name that says what is tested; arrange, act and assert kept separate; no dependence on existing data; and an assertion that would actually fail if the code were wrong. The last point caught more problems than any other. A test that asserts only that no exception was thrown passes for almost any implementation. Prudence's first test for the alert queue had done exactly that, and Desmond asked her to assert the number of queued rows and the line numbers instead.

Worked problem

Testing the alert queue change

Prudence has rewritten the alert queue insert with insert_recordset and a notexists join. Which tests should she write before opening the pull request?

Show solution
  1. Create a test class in CobaltRidgeCustomTests with the SysTestTransaction attribute set to automatic rollback.
  2. In setUp, create a vendor, an item flagged for inspection and a purchase order header with ATL.
  3. Write one test per case: no certificate is queued, Received is not, Waived is not, and a line not requiring inspection is never queued.
  4. Name each test for its condition and expected result, with one assertion on the queue contents.
  5. Run the tests in Test Explorer and make sure each fails when the code is deliberately broken.

Answer: Four small, isolated tests describe the rule completely, run in seconds, and caught the Waived case that the first version of the join missed.

Common mistakes

  • MistakeRelying on records that already exist in the environment.

    InsteadCreate all test data in the test, with ATL or helpers, and let automatic rollback remove it.

  • MistakeChecking many behaviours in one test.

    InsteadWrite one behaviour per test with a descriptive name.

  • MistakePutting test classes in the production model.

    InsteadKeep tests in a separate test model that is not deployed to production.

  • MistakeKeeping a test that fails at random.

    InsteadFix or delete unreliable tests at once so that failures are trusted.

Summary and key terms

  • SysTest test classes extend SysTestCase and use assertion methods; Test Explorer runs them in Visual Studio.
  • The SysTestTransaction attribute with automatic rollback keeps tests isolated; setUp and tearDown run around each test.
  • Tests live in a separate model, and the Acceptance test library helps create standard data and run processes.
  • Task recorder recordings can generate form tests that need editing and assertions.
  • Tests on wrappers and handlers through standard processes protect extensions across service updates.
SysTestCase
The base class for X++ unit test classes.
Test Explorer
The Visual Studio window that lists, runs and reports tests.
SysTestTransaction
An attribute that sets how a test class handles database transactions, such as automatic rollback.
Acceptance test library (ATL)
A Microsoft library of classes for creating test data and running business processes in tests.
Test model
A separate model that holds test code and is excluded from production packages.

Practice problems

Work each problem on paper first, then reveal the answer to check.

  1. Which method runs before each test in a SysTest class?

    Show answer

    setUp.

  2. Why did Desmond want wrapper tests to run through the standard process?

    Show answer

    So that a service update that stops calling the wrapper makes a test fail.

  3. What should a developer do with a generated Task recorder test?

    Show answer

    Rename it, remove incidental steps and add assertions.

Lesson quiz · 5 questions

Score 60% or more to complete this lesson.

Take the quiz