1
0
mirror of https://github.com/actix/actix-website synced 2024-12-02 19:52:23 +01:00
actix-website/content/docs/testing.md
tdeith 6ffed2a63e
Update testing.md
Change moves hyperlink to hit `struct.TestRequest` instead.
2020-05-20 12:11:51 -07:00

2.0 KiB

title menu weight
Testing docs_advanced 215

Testing

Every application should be well tested. Actix-web provides tools to perform unit and integration tests.

Unit Tests

For unit testing, actix-web provides a request builder type. TestRequest implements a builder-like pattern. You can generate a HttpRequest instance with to_http_request() and call your handler with it.

{{< include-example example="testing" file="main.rs" section="unit-tests" >}}

Integration tests

There a few methods for testing your application. Actix-web can be used to run the application with specific handlers in a real http server.

TestRequest::get(), TestRequest::post() and other methods can be used to send requests to the test server.

To create a Service for testing, use the test::init_service method which accepts a regular App builder.

Check the api documentation for more information.

{{< include-example example="testing" file="integration_one.rs" section="integration-one" >}}

If you need more complex application configuration testing should be very similar to creating the normal application. For example, you may need to initialize application state. Create an App with a data method and attach state just like you would from a normal application.

{{< include-example example="testing" file="integration_two.rs" section="integration-two" >}}

Stream response tests

If you need to test stream it would be enough to call take_body() and convert a resulting ResponseBody to future and execute it. For example of testing Server Sent Events.

{{< include-example example="testing" file="stream_response.rs" section="stream-response" >}}