Run Test of Element Execution
For writing tests, we recoommend Groovy and JUnit. Although Groovy and JUnit are sufficient, we also recommend to use the Spock framework as it brings a huge amount of very helpful features to the tests.
Assume there is a logic PricingLogic that has Cost element, Margin element and CostPlus element that calculates price using values from previous elements cost and margin:
def cost = out.Cost
def margin = out.Margin
if (cost && margin) {
return cost * (1 + margin)
}
To create a unit test, click the unit test icon in the logic editor in Studio. Once the test script is created, the unit test icon is displayed next to the element name. Click that icon to open the script file.
Studio creates a template of groovy unit test script in the folder CalculationLogicTest/<logic_name>/<element_name>Test. The template only checks that the result of an element execution is not null. You are supposed to implement the desired condition.
Now we will do the following:
Line 11: Provide some meaningful name of the test. For example “CostPlus calculation“.
Line 13-14: Supply the faked values of elements Cost and Margin by adding .withElementResult()
method calls.
Line 22: Adjust the test condition and provide the real value. In our case we want to result value to be qeual to 19.558.
package PricingLogic
import net.pricefx.tdd4c.TestRun
import spock.lang.Specification
class CostPlusTest extends Specification {
def LOGIC_DIR = "PricingLogic+2020-01-01"
def ELEMENT_NAME = "CostPlus"
def "CostPlus calculation"() {
when:
TestRun testRun = TestRun.builder()
.withElementResult("Cost", 15.4)
.withElementResult("Margin", 0.27)
.buildElementTest(LOGIC_DIR, ELEMENT_NAME)
and:
Script script = testRun.getElementScript()
then:
testRun.execute()
.getElementTestResult() == 19.558
}
}
To provide faked values for Cost and Margin use two calls of the method .withElementResult(String elementName, Object resultValue)
, but more practical will be to use method .withElementResults(Map<String, Object> elementResultsMap)
and provide the map of faked element result values for all elements at once:
.withElementResults([
Cost : 15.4,
Margin: 0.27,
])
Now click the test run icon next to the test name to run this test or click the test icon next to the class name run all tests in the file. Select Run from the context menu:
If the test passed a green check icon is displayed next to the test name and the script finishes with exit code 0.
Lets modify the value on the line 23 and put a wrong value there.
If the test did not pass a warning icon is displayed next to the test name and IntelliJ IDEA will show you the values of all the expressions of the test condition that failed.
For more complex results, you can click the hyperlink “Click to see difference” to see all details.
Found an issue in documentation? Write to us.