In automated unit testing, it is sometimes necessary to use objects or procedures that look and behave like their release-intended counterparts, but are actually simplified versions that reduce complexity and facilitate testing. Such procedures are called test doubles. Mocking refers to the idea of providing these test doubles instead of the real implementation during tests. This helps in reducing the testing effort in cases where testing could be too cumbersome, or it is not possible to instantiate the entire program.
Furthermore, as we discussed with the testing pyramid, doing more unit tests is preferable during the development of the application as it forces application developers to write more testable application code and apply separation of concerns more thoroughly, which usually leads to more maintainable and understandable code. Using mocking and the tools provided by SAP Cloud SDK, we can test a small portion of the code without the need for a real SAP S/4HANA back-end system. This provides a very convenient way to test the overall functionality.
The MockUtil is a mocking utility class; it is provided by the SAP Cloud SDK. The MockUtil class helps create the mock instances required to simulate instances. The MockUtil class provided by the SAP Cloud SDK can also deal with connectivity to an SAP S/4HANA back-end.
To implement mocking using the MockUtil class (in Java), you need to:
- Create a new test file under your project location – <project>/unit-tests/src/test/java
- Initialize the mocking facility MockUtil provided by the SAP Cloud SDK
- Declare an initialization method beforeClass() which is annotated with @BeforeClass. This means that this method is called exactly once before the execution of all other test methods. Inside the method, all the required SAP Cloud Platform mocks are initialized (tenant, user, etc)
- Inside the method beforeClass(), mock a dummy SAP S/4HANA destination
- Inside the method beforeClass(), initialize the testing parameters
- Lastly add another method inside the newly created file to do the actual first testing. Inside this method we do the actual mocking by defining under which condition what should happen