.json
approved files using Shouldly and Newtonsoft.JsonApproval tests, also called characterization tests in WELC, is a very useful tool when working on existing code which does not have tests.
Here are some ways to make the approval files (or golden master) easier to read when writing approval tests for Web APIs which returns JSON as response data:
Configure the assertion tool to produce an approval file with .json
extension instead of a .txt.
extension. When using Shouldly for example, use this code:
content.ShouldMatchApproved(c => c.WithFileExtension(".json"));
JSON-format the response data before the approval phase of the test. Newtonsoft.Json can be used to do that:
string jsonStringFromatted = JToken.Parse(jsonString)
.ToString(Formatting.Indented);
Doing that produces a properly formatted .approved.json
file which looks like this..
{
"employee": {
...
"name": "Juan dela Cruz",
"email": "juandelacruz@example.com"
}
}
.. instead of the harder to read .approved.txt
file..
{"employee":{..."name":"Juan dela Cruz","email":"juandelacruz@example.com"}}
Here is a more complete approval test sample:
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Shouldly;
using System.Net.Http;
using System.Threading.Tasks;
using Xunit;
...
public class CreateEmployeeTests : ApprovalTestBase
{
[Fact]
public async Task Succeeds_if_happy_path()
{
...
var payload = ...
var response = await httpClient.PostAsJsonAsync("/api/employee...", payload);
string content = JToken.Parse(await response.Content.ReadAsStringAsync())
.ToString(Formatting.Indented);
content.ShouldMatchApproved(c => c.WithFileExtension(".json"));
}
...
}