Write unit tests for scripts
From version 1.1.0 and later, the Sitecore Content Hub CLI lets you write and execute unit tests for your scripts using xUnit.net and NSubstitute.
When using [Theory], [InlineData] is currently the only way of providing arguments to the test method.
This walkthrough describes how to:
Create a script
In your working directory, create a script with the name MyScript.csx:
Create a test script
Unit test scripts are located in the unit-tests directory within the working directory and are expected to be named after the script that they are testing (for example, MyScript.csx). For that reason, it is important to have one test script for each script.
In the unit-tests directory, create a script matching the name of the script to test:
The file structure should now be the following:
Explanation of the test script code
-
Create a named test method. The
[Fact]attribute tells the test runner that this method is a unit test: -
Create mocks of the required objects that will be passed down to the actual script. This sets the context for different scenarios as well as mimic API calls that are being done through the
MClientinstance within the script. In this example, theTargetproperty of the context is explicitly set tonull: -
Compiles and executes the related script (based on the file name) and passes the
clientandcontextinstances down. When following the commonly used AAA (Arrange - Act - Assert) pattern, this call would be the Act section: -
Verify that the conditions of the test are met. In this case, an error message should have been logged.
Run unit tests
You can either run all unit tests at once, or you can run a single unit test:
-
To run all unit tests, use the following code:
-
To run a single unit test, use the following code: