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 (see figure 6.1).

Figure 6.1 The builder from this chapter is used for an example struct
figure

6.1 Builder macro project setup

6.2 Fleshing out the structure of our setup

6.3 Adding white-box unit tests

6.4 Black-box unit tests

6.4.1 A happy path test

6.4.2 A happy path test with an actual property

6.4.3 Testing enables refactoring

6.4.4 Further improvements and testing

6.4.5 An alternative approach

6.4.6 Unhappy path

6.5 What kinds of unit tests do I need?

6.6 Beyond unit tests

6.7 From the real world

Exercises

Summary