14 Testing and building your code from tests

 

This chapter covers

  • Using crates and modules to structure your code and limit how others can use it
  • Using testing to prove that your code runs as it should
  • Using test-driven development by writing the tests first and then the code

As your code grows, you’re going to want to think about its structure. The more you write, the more you’ll find that some code belongs in its own space, separate from other bits of code. You’ll also want to start testing your code as it grows because even Rust’s strict compiler can’t protect you from logic errors. Tests also help to remind you when you change your code if something has gone wrong. Writing tests can be a bit boring at times, but, in general, the more tests you have to catch problems, the better. We’ll also learn test-driven development (TDD), which means to write the tests before you write any code! In TDD, you write your tests, which will all fail. Only then, you write your code to make the tests pass one by one until finally everything works the way you intended.

14.1 Crates and modules

14.1.1 Module basics

14.1.2 More on how the pub keyword works

14.1.3 Modules inside modules

14.2 Testing

14.2.1 Just add #[test], and now it’s a test

14.2.2 What happens when tests fail

14.2.3 Writing multiple tests

14.3 Test-driven development

14.3.1 Building a calculator: Starting with the tests

14.3.2 Putting the calculator together

Summary