Macro use case – writing tests
Macros are used quite a lot when writing test cases for unit tests. Let's say you were writing a HTTP client library and you would like to test your client on various HTTP verbs such as GET
or POST
and on a variety of different URLs. The usual way you would write your tests is to create functions for each type of request and the URL. However, there's a better way to do this. Using macros, you can cut down your testing time by many folds by building a small DSL to perform the tests, which is readable and can also be type checked at compiled time. To demonstrate this, let's create a new crate by running cargo new http_tester --lib
, which contains our macro definition. This macro implements a small language that's designed for describing simple HTTP GET
/POST
tests to a URL. Here's a sample of what the language looks like:
http://duckduckgo.com GET => 200 http://httpbin.org/post POST => 200, "key" => "value"
The first line makes a GET
request to duckduckgo...