6 Testing a builder macro
This chapter covers
- Writing a derive macro that will generate a builder for structs
- Creating white-box tests to verify the behavior of functions within your macro
- Using black-box tests that take an outside view of your code
- Deciding what types of tests are most useful for your macro
The builder pattern is a very convenient, fluent way of constructing structs. Because of that, it is omnipresent in Rust code. Often, though, the code required to write a builder is boilerplate. Boilerplate that we can automate away! In this chapter, we will write a macro to do just that. Because we are not touching the original struct, we can use a derive macro (remember, go for the simplest option). In an implementation block, we create a temporary Builder struct that stores information and offers a build method for creating the original struct.
Figure 6.1 The builder from this chapter for an example struct
This is not an original idea, sprung wholly from my head in all its glory. There is, for example, a procedural macro workshop where you create this kind of macro on GitHub and the Crust of Rust walks you through one possible implementation. Being original is thus not the point of this chapter. Instead, while implementing this builder we will discuss how we can test procedural macros. And ideally, such a chapter would be written using Test Driven Development.