1
0
mirror of https://github.com/actix/actix-website synced 2024-11-30 19:14:36 +01:00
actix-website/content/docs/testing.md

53 lines
2.1 KiB
Markdown
Raw Normal View History

2018-05-22 23:15:08 +02:00
---
title: Testing
menu: docs_advanced
weight: 215
2018-05-22 23:15:08 +02:00
---
# Testing
2019-06-24 23:43:31 +02:00
Every application should be well tested. Actix-web provides tools to perform unit and
2018-05-22 23:15:08 +02:00
integration tests.
# Unit Tests
For unit testing, actix-web provides a request builder type.
[*TestRequest*][testrequest] implements a builder-like pattern. You can generate a
`HttpRequest` instance with `to_http_request()` and call your handler with it.
2019-06-17 21:39:58 +02:00
{{< include-example example="testing" file="main.rs" section="unit-tests" >}}
2018-05-22 23:15:08 +02:00
# Integration tests
2020-07-05 18:23:46 +02:00
There are a few methods for testing your application. Actix-web can be used
2020-09-12 17:21:54 +02:00
to run the application with specific handlers in a real HTTP server.
2018-05-22 23:15:08 +02:00
`TestRequest::get()`, `TestRequest::post()` and other
2018-05-22 23:15:08 +02:00
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
2019-06-24 23:43:31 +02:00
regular `App` builder.
2018-05-22 23:15:08 +02:00
2020-09-12 17:21:54 +02:00
> Check the [API documentation][actixdocs] for more information.
2018-05-22 23:15:08 +02:00
2019-06-17 21:39:58 +02:00
{{< include-example example="testing" file="integration_one.rs" section="integration-one" >}}
2018-05-22 23:15:08 +02:00
2020-07-05 18:23:46 +02:00
If you need more complex application configuration, testing should be very similar to creating
2019-06-24 23:43:31 +02:00
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.
2018-05-22 23:15:08 +02:00
2019-06-17 21:39:58 +02:00
{{< include-example example="testing" file="integration_two.rs" section="integration-two" >}}
2018-05-22 23:15:08 +02:00
2018-05-23 22:35:42 +02:00
# Stream response tests
2020-07-05 18:23:46 +02:00
If you need to test stream generation, it would be enough to call `take_body()` and convert a
resulting [*ResponseBody*][responsebody] into a future and execute it, for example when testing
[*Server Sent Events*][serversentevents].
2018-05-23 22:35:42 +02:00
2019-06-17 21:39:58 +02:00
{{< include-example example="testing" file="stream_response.rs" section="stream-response" >}}
[serversentevents]: https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events
2020-09-12 17:21:54 +02:00
[responsebody]: https://docs.rs/actix-web/3/actix_web/body/enum.ResponseBody.html
[actixdocs]: https://docs.rs/actix-web/3/actix_web/test/index.html
[testrequest]: https://docs.rs/actix-web/3/actix_web/test/struct.TestRequest.html