14 Testing and building your code from tests

 

This chapter covers

  • Crates and modules - Structuring your code and limiting how others can use it
  • Testing - Proving that your code runs as it should
  • Test-driven development - Writing the tests first, 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 too as it grows, because even Rust's 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. And 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

First we are going to learn about where to put your code, what parts to make pub, and so on.

14.1.1 Module basics

14.1.2 More on how the pub keyword works

14.1.3 Mods inside mods

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 (TDD)

14.3.1 Building a calculator: starting with the tests

14.3.2 Putting the actual calculator struct together

14.4 Summary