Creating Test Doubles

TestDoubles are objects that we pass to the test run that interact with the code under test, i.e., all injected variables (api, quoteProcessor, rebateManager, ...).

The test double can be a fake or a mock. By default, when no test doubles are provided, some default fakes are injected to the elements to allow the code execution. However, the test doubles need to be configured per test.

I Warned You!

Whenever a test double is needed to provide some dependency, it is strongly recommended that you change the code so that it passes the dependency value to a new function as a parameter and then you test just this new function. This way it is much easier to test and maintain in future.

Map Based Fakes

By default, we use fake objects created as maps. These default fake objects are defined in the upstream tdd4c library. In a test, you can override properties on these fakes to provide the test specific behavior.

TestRun testRun = TestRun.builder() .withElementResult("NotComputedElement", "HardCodedValue") .withLogicTestDouble("api", [ find: { typeCode -> [[attribute1: "a"],[attribute1: "b"],[attribute1: "c"]] } ]) .buildLogicTest("MyLogic3")

This code will ensure that the default fake for API variable has overridden the find function that will be called in a test. Whenever MyLogic3 is executed, it takes the default map based fake and adds the behavior specified in .withLogicTestDouble. This way you can create test doubles with minimal effort.

There is also the .withElementTestDouble method. It specifies the overrides for the default + logic test double to be provided in a single element.

The methods api.getElement and api.getBinding are handled gracefully in TestRun and should always provide the expected result. There should not be any need to implement it manually.

Object Based Fakes

If map based fakes cannot be used, you can provide object based implementation. This should be needed only when there is a collision of some Groovy default method (e.g. groupBy()) with the defined test double. No merging of the element test double with the logic test doubles will happen with the object based fakes.

Mocks

There are a few PFX interfaces bundled with the tdd4c library. PublishedApi, DatamartContext and TableContext to name some of them. You can use the Mockito library to create mocks and pass them as the test double. No merging of the element test double with the logic test double will happen in this case.

PublishedAPI api = mock(PublishedAPI) when(api.find(anyString())).thenReturn([[attribute1: "a"],[attribute1: "b"],[attribute1: "c"]]) TestRun testRun = TestRun.builder() .withElementResult("NotComputedElement", "HardCodedValue") .withLogicTestDouble("api", api) .buildLogicTest("MyLogic3")

Found an issue in documentation? Write to us.

Â