Sending and Checking Json
TIP
As of Alba v5, the Json serialization is done with the configured input and output formatters within the underlying application. This means that Alba can support systems using both System.Text.Json and Newtonsoft.Json.
Sending Json
Since posting Json to a web server API is so common, Alba has some helpers for writing Json to the request:
public Task send_json(IAlbaHost host)
{
return host.Scenario(_ =>
{
// This serializes the Input object to json,
// writes it to the HttpRequest.Body, and sets
// the accepts & content-type header values to
// application/json
_.Post
.Json(new Input {Name = "Max", Age = 13})
.ToUrl("/person");
});
}
Reading Json
To deserialize the response body with Json to interrogate the results in a strong typed way, use this syntax:
public async Task read_json(IAlbaHost host)
{
var result = await host.Scenario(_ =>
{
_.Get.Url("/output");
});
// This deserializes the response body to the
// designated Output type
var output = result.ReadAsJson<Output>();
// do assertions against the Output model
}
You can also use a shorthand syntax to skip Scenario()
like this:
public async Task read_json_shorthand(IAlbaHost host)
{
var output = await host.GetAsJson<Output>("/output");
// do assertions against the Output model
}
This code snippet is functionally identical to the previous usage.
Shortcut for Pure Json Services
If you don't care about any additional HTTP headers or need to verify any HTTP status code except for 200 Ok
, you can use this shorthand syntax to quickly post and receive results from a web service:
[Fact]
public async Task post_and_expect_response()
{
using var system = AlbaHost.ForStartup<WebApp.Startup>();
var request = new OperationRequest
{
Type = OperationType.Multiply,
One = 3,
Two = 4
};
var result = await system.PostJson(request, "/math")
.Receive<OperationResult>();
result.Answer.ShouldBe(12);
result.Method.ShouldBe("POST");
}
There are similar helpers for other HTTP verbs like PUT
and DELETE
.