We need a way to tell that what weβve been writing so far is correct. Testing is straightforward in Rust. We donβt need to create a separate test file. Right at the bottom of quiz/src/quiz.rs
, add the following:
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_question_is_answered() {
let q = Question {
title: String::from("Is this a question?"),
answer: true,
user_answer: Some(true)
};
assert_eq!(q.is_answered(), true);
}
#[test]
fn test_question_is_correct() {
let q = Question {
title: String::from("Is this a question?"),
answer: true,
user_answer: Some(true)
};
assert_eq!(q.is_correct(), true);
}
}
Read more about testing in Rust here.
To run the tests, do:
cargo test -p quiz
Youβll notice that no tests are run. Thatβs because quiz.rs
is not being used in the project. We need to add it to main.rs
. Add the following to the very top of main.rs
:
mod quiz;
Now try to run the test again.
Thatβs not all, exercise
Surely, those two tests are not enough. Implement additional tests to cover:
- Moving to next question for a quiz
- Moving to previous question for a quiz
- Answering a question from a quiz
- Counting score