Skip to content

Mocks in CobolCheck

Dave Nicolette edited this page Feb 11, 2021 · 9 revisions

Home -> User Guide -> Mocks and Stubs ->

This document was last updated on February 11, 2021.

Cobol Check replaces all I/O-related Cobol statements with comments in the program under test. You can specify a mock in your test suite when you want specific behavior to occur when the program under test attempts an I/O operation, such as:

  • populating a Working-Storage area with the contents of a fake file record;
  • simulating an I/O error, such as a "file not found" condition;
  • simulating a successful write operation; or
  • counting the number of times the program under test attempted a particular I/O operation.

You may wonder how you can test against files when we stub all I/O operations. The answer is that tests that operate against files are not "unit" tests; they are functional tests of some sort, but they are at a higher level of abstraction than unit tests. See What is a Unit Test? for more information. By definition, a unit test does not touch files.

You don't need a special tool like cobol-check to run tests against files and databases. Unit-level checking as supported by cobol-check is a missing piece of the puzzle for Cobol, but other levels of checking are already feasible using existing tools. See Component and Integration Testing for more information.

Mocks in cobol-check

In cobol-check, stubs and mocks are the same. There is only one keyword, MOCK. There is no keyword, STUB. The conceptual difference is that a mock includes some behavior (Cobol statements) that a test case wants to happen as part of the conditions surrounding the test.

In addition, in cobol-check a mock keeps track of the number of times the code under test invokes it. Our test cases can then check whether the result is as expected, as well as whether the mocked resource has been invoked some particular number of times during test execution.

In cobol-check, we always specify MOCK even if our intent, conceptually, is to stub a resource.

So, a stub looks like this:

    MOCK FILE MY-FILE
    END-MOCK

and mocks look like this:

    MOCK FILE FIRST-FILE
        ON OPEN 
            STATUS IS FILE-NOT-FOUND
        ON CLOSE
            STATUS IS NOT-OPEN
    END-MOCK

    MOCK FILE SECOND-FILE
        ON READ
            MOVE 'AAAAABBBBBCCCCCDDDDDEEEEE' TO WS-RECORD-AREA
    END-MOCK

Why use a stub?

If we stub all I/O statements anyway, then why bother specifying a file mock that doesn't inject any behavior into the program under test? The reason is to use the VERIFY keyword to check the number of accesses to the stubbed resource, like this:

    MOCK FILE SALES_TAX_FILE 
        ON READ TALLY ACCESSES 
    END-MOCK
    MOCK FILE ERROR_LOG
        ON WRITE TALLY ACCESSES
    END-MOCK
    PERFORM 4000-APPLY-SALES-TAX THRU 4999-END 
    VERIFY SALES_TAX_FILE WAS READ AT LEAST ONCE 
    VERIFY ERROR-LOG WAS NEVER WRITTEN
Clone this wiki locally