The Autogenerated Contract Check

Use the contract checking test to ensure assertions are not violated. Assertions are parameter limits or restrictions that should be obeyed, but which are very often not explicitly enforced by the code. For example, it surely makes sense that a phone number never has zero digits. If that is the case then calling the PhoneNumber constructor with a value of 0 should violate this assertion. You will create this assertion.

To complete the test script:

  1. In the Project Browser tab, double-click the node PhoneNumber.otc

  2. Maximize the test script editor

This is the C++ component testing contract checking script. In it you will perform those steps necessary to verify that assertions are not violated.

Contract checking scripts are written with a compiler-independent test script API. For detailed information about the script layout, take advantage of the OneTest Embedded Reference Guide. For this Tutorial, only critical script elements will be discussed.

For each class a CLASS block is created and this CLASS block can test for violations of:

Since you wish to verify that the length of the phone number always exceeds 0, then one possible contract check would be to ensure the stringLength variable of the PhoneNumber constructor is always greater than 0 (have a look at the source code if you wish to verify this approach yourself).

  1. Scroll down the contract checking test script until you see the line:

WRAP PhoneNumber(unsigned int length)

REQUIRE ("Require PhoneNumber")

ENSURE ("Ensure PhoneNumber")

  1. Modify the code as follows:

WRAP PhoneNumber(unsigned int length)

//REQUIRE ("Require PhoneNumber")

ENSURE (stringLength > 0)

 

  1. From the File menu, select Save.

The WRAP keyword lets you check for pre- and post-conditions of a class method. The REQUIRE keyword checks pre-conditions; the ENSURE keyword checks post-conditions.

Another example of a contract check would be to verify that class invariants are never violated. For example, it certainly makes sense that the phone number can never be full and empty at the same time. This can never be, it is an invariant. The PhoneNumber class actually has these methods - isFull() and isEmpty() - so use them to verify this assertion.

  1. Scroll up the contract checking test script until you see the line

// INVARIANT (/* expression */);

  1. Modify this line as follows:

INVARIANT (!(isFull() && isEmpty()));

  1. Select the menu item File->Save

Done. You are ready to compile and run the test and contract check.