Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Info

NOTE: Function return calculated result for this sample == 11.5.

...

Complex Test Definitions

The test definitions cover various scenarios, including mocking API functions such as findLookupTable or find, mocking the "stream," mocking the result of another element, mocking api.global or api.local variables, mocking functions from a shared library, testing a function that modifies local or global tables and always returns null, and testing a function using a function from another element.

This section contains following sample test definition:

  • how to mock Mock api function, e.g. findLookupTable or find.

  • how to mock Mock stream

  • how to mock Mock another element result

  • how to mock Mock api.global or api.local variables

  • how to mock Mock function from (shared) Library

  • how to test Test function if it modifies local or global table and always returns null

  • how to test Test function using function from another element

How to mock api function

...

Mock Pricefx API functions

Mocking Pricefx API functions covers various aspects such as mocking API functions, testing function behavior with different inputs, and mocking global or local variables. It also includes examples of mocking "api.stream" and another element's result. Additionally, it addresses challenges related to function testing and provides insights into complex test definitions.

Mock findLookupTable or find (or any other)

You can do it via Mocking the findLookupTable function includes examples of how to mock this function using the withLogicTestDouble function or as part of withLogicTestDoublesfunction. See the line 13 in this sample. Function withLogicTestDoubles simply contains “api” map, with mocked api . It also provides insights into testing functions that modify local or global tables and always return null, as well as mocking other elements' results. Additionally, it addresses the mocking of API functions, such as findLookupTable or find, and how to mock "api.stream" and api.global or api.local variables.

For example, we can do it via withLogicTestDouble function or as part of withLogicTestDoubles function. The function withLogicTestDoubles simply contains “api” map, with mocked api functions.

Code Block
    def "getRetailerSIRecords returns records as array of maps with values in big decimal"() {
        when:

        def countryArray = ["FRANCE", "ROMANIA"]
        def extTyreId = "515145"
        def startMonthExternalPricingSI = "201901"
        def endMonthExternalPricingSI = "202401"
        def globalTable = ["EU3CountryArray": [["attribute1": "FRANCE", "attribute11": "FRANCE",], ["attribute1": "ROMANIA", "attribute11": "ROMANIA"]]]

        TestRun testRun = TestRun.builder()
                .withLogicTestDoubles(["api": [
                        "global"                : globalTable,
                        "findLookupTable"       : { String name -> return ["id": "10"] },
                        "getMaxFindResultsLimit": { -> return 200 },
                        "find"                  : { String typecode, Integer start, Integer end, String sortBy, def fieldsList, def filter1, def filter2, def filter3, def filter4, def filter5 ->
                            return [
                                    ["key1": "FRANCE", "attribute10": "64.6"],
                                    ["key1": "FRANCE", "attribute10": "64.6"],
                                    ["key1": "FRANCE", "attribute10": "64.6"],
                                    ["key1": "FRANCE", "attribute10": "64.6"],
                                    ["key1": "FRANCE", "attribute10": "64.6"],
                                    ["key1": "ROMANIA", "attribute10": "63.4620732"],
                                    ["key1": "ROMANIA", "attribute10": "63.4620732"]
                            ]
                        }

                ], "libs"                   : getSharedLibrary()])
                .buildElementTest(LOGIC_DIR, ELEMENT_NAME)
        then:
        testRun.getElementScript().getRetailerSIRecords(countryArray, extTyreId, startMonthExternalPricingSI, endMonthExternalPricingSI) == [
                [Country: "FRANCE", RetailerSIPriceEUR: 64.6],
                [Country: "FRANCE", RetailerSIPriceEUR: 64.6],
                [Country: "FRANCE", RetailerSIPriceEUR: 64.6],
                [Country: "FRANCE", RetailerSIPriceEUR: 64.6],
                [Country: "FRANCE", RetailerSIPriceEUR: 64.6],
                [Country: "ROMANIA", RetailerSIPriceEUR: 63.4620732],
                [Country: "ROMANIA", RetailerSIPriceEUR: 63.4620732]]

    }

How to mock “api.stream”

Simply - define api.stream the same way as other api function, and add “.stream()” at the end of values list. Sample here, see the line 26.

...

languagegroovy

...

Tip

CODE REVIEW: snippet of code from a test script written in Groovy, it defines a test case for a method named getRetailerSIRecords that is expected to return an array of maps with values in BigDecimal format.

Here's a breakdown of the key parts of the script:

  • Lines 4-7 define variables for the parameters that will be passed to the getRetailerSIRecords method. These include arrays of countries (countryArray), an external tire ID (extTyreId), and date ranges for external pricing (startMonthExternalPricingSI and endMonthExternalPricingSI).

  • Line 8 sets up a globalTable map with key-value pairs

  • Lines 9-27 construct a TestRun object using a builder pattern. The TestRun is configured with logic test doubles for mocked API calls, such as findLookupTable, getMaxFindResultsLimit, and find. The find method seems to be stubbed to return a hardcoded list of maps with country keys and corresponding attribute10 values representing prices.

  • Lines 28-29 indicate that the test is built for a specific logic directory (LOGIC_DIR) and element name (ELEMENT_NAME), which are placeholders for actual paths or identifiers.

  • Lines 30-38 show the then: section where the actual test execution takes place.

  • The getRetailerSIRecords method is called with the previously defined parameters, and the expected output is an array of maps with countries and their corresponding RetailerSIPriceEUR values in BigDecimal format. The prices for "FRANCE" are consistently "64.6", while prices for "ROMANIA" are "63.4620732".

This test case appears to validate that the method correctly retrieves and formats pricing information for different countries within specified date ranges. The use of BigDecimal is important for financial calculations to avoid precision loss associated with floating-point arithmetic.

Mock of api.stream

Mocking the api.stream function includes defining api.stream similarly to other API functions and adding ".stream()" at the end of the values list. It also provides examples of testing functions that modify local or global tables and always return null, as well as mocking another element's result.

Additionally, it addresses more complex test definitions, such as mocking API functions like findLookupTable or find, function testing using a function from another element, and mocking global or local variables.

For example, in the following sample we will define api.stream the same way as other api function, and add “.stream()” at the end of values list.

Code Block
languagegroovy
    def "getPXasMap return map with specified attribute as key"() {
        when:
        TestRun testRun = TestRun.builder()
                .withLogicTestDouble("api", [
                        "getMaxFindResultsLimit": { -> return 200 },
                        "stream"                : { String typeCode, def orderBy, def fields, def filters ->
                            return [
                                    [
                                            "attribute18": "*",
             : { String typeCode, def orderBy, def fields, def filters ->                     "attribute17": "*",
       return [                                     ["attribute39": "*",
                                            "attribute18attribute37": "*",
                                    ],
                                   "attribute17": "*", [
                                            "attribute39attribute18": "*SNOW",
                                            "attribute37attribute17": "*RIKEN",
                                    ],        "attribute39": "PC",
                           [                 "attribute37": "Winter"
                          "attribute18": "SNOW",         ],
                                   "attribute17": "RIKEN", [
                                            "attribute39attribute18": "PCENERGY SAVER",
                                            "attribute37attribute17": "WinterMICHELIN",
                                    ],        "attribute39": "PC",
                            [                "attribute37": "Summer"
                            "attribute18": "ENERGY SAVER",      ]
                            ].stream()
         "attribute17": "MICHELIN",              }
                ])
             "attribute39": "PC",  .buildElementTest LOGIC_DIR, ELEMENT_NAME

        and:
        Script script = testRun.getElementScript()

        then:
        script.getPXasMap("attribute37CommercialCatalog":, "Summerattribute18"
                           , ["attribute18", "attribute17", "attribute37", "attribute39"]) == ["*"         ]  : ["attribute18": "*", "attribute17": "*", "attribute39": "*", "attribute37": "*"],
                  ].stream()                         }                 ])                 .buildElementTest LOGIC_DIR, ELEMENT_NAME          and:         Script script = testRun.getElementScript()          then:         script.getPXasMap("CommercialCatalog", "attribute18", ["attribute18", "attribute17", "attribute37", "attribute39"]) == ["*"   "SNOW"        : ["attribute18": "*SNOW", "attribute17": "*RIKEN", "attribute39": "*PC", "attribute37": "*Winter"],
                                                                                                                                "ENERGY SAVER": ["attribute18": "ENERGY SAVER", "attribute17": "MICHELIN", "attribute39":          "SNOW"        : ["attribute18": "SNOW", "attribute17": "RIKEN", "attribute39": "PC", "attribute37": "Winter"],
                                                                                                                                "ENERGY SAVER": ["attribute18": "ENERGY SAVER", "attribute17": "MICHELIN", "attribute39": "PC", "attribute37": "Summer"]]
    }

...

"PC", "attribute37": "Summer"]]
    }

Tip

CODE REVIEW: a code snippet from a test script written in Groovy, which is a scripting language that runs on the Java Virtual Machine (JVM). The script defines a method called getPXasMap which seems to be designed to return a map with a specified attribute as a key.

In this code we can discern the following:

  • The method is being tested using a TestRun object that is built with mock responses for an API. The mock API is set up to return specific values when the getMaxFindResultsLimit and stream methods are called.

  • The stream method in particular is mocked to return a list of maps, each containing attributes with keys like "attribute18", "attribute17", "attribute39", and "attribute37", and corresponding values such as "SNOW", "RIKEN", "PC", and "Winter" for one entry, and "ENERGY SAVER", "MICHELIN", "PC", and "Summer" for another.

  • The buildElementTest method seems to be used to prepare the test environment, specifying a logic directory and an element name.

Info

NOTE: In the assertion part of the script (then block), it is expected that when the getPXasMap method is called with the parameters "CommercialCatalog", "attribute18", and a list of attributes, it will return a map where the keys are the values of "attribute18" and the values are the corresponding maps of attributes.

The expected outcome of the method is:

  • A map with keys like "*", "SNOW", and "ENERGY SAVER", each pointing to their respective maps containing various attributes and their values.

This is a typical pattern for writing unit tests in software development, where you set up conditions, invoke the method under test, and assert that the output matches your expectations.

Mock another Element Result

This is very common case - element or functions is using another element result and you have to mock it to your rest. You can simply do it with “out” map like this. See the line 5 and below.

...