Introduction to Mocks in Rust

Introduction to Mocks

As we progress in our understanding of isolating dependencies with test doubles, we've already covered dummies and stubs. In this lesson, we introduce mocks, powerful tools for simulating external dependencies in software tests. In previous lessons, we discussed dummies and stubs, which allow you to put something in place of a dependency. However, mocks allow us to replicate the behavior of complex systems, enabling testing and verification in isolation without dependence on unpredictable systems like databases or web services.

Adhering to the TDD workflow remains crucial:

  • Red: Start with a failing test.
  • Green: Implement just enough code to pass the test.
  • Refactor: Clean up your code without altering its functionality.

Using Rust and the mockall library, we'll demonstrate how mocks are applied to effectively isolate and test application logic.

Why Use Mocks in TDD?

Mocks are essential in TDD, as they allow you to test code independently of the system parts you don't control. When constructing tests for a PricingService, for instance, you might mock an external currency conversion service to avoid failures due to downtime or unexpected changes in the API. Mocks create a controlled environment where various conditions and responses can be simulated, and calls can be validated.

Unlike stubs that merely return data, mocks fully simulate dependencies by preventing the actual code or functionality from executing and providing validation that the mock was called. For example, if a function interacts with an external API, a mock could simulate that API's response without making any network requests and verify the API was called with specific parameters.

Mocking Fundamentals with Mockall

We'll now explore mocking fundamentals using the mockall crate in Rust. We'll initiate by understanding how to create mocks and set up expectations using Rust's capabilities.

Consider the ExchangeRateService, responsible for fetching exchange rates from an API. When testing the PricingService, mocking this service ensures that tests do not depend on real API interactions.

Below is an example using mockall and #[automock] for setting up a test:

use mockall::{automock, predicate::*};
use anyhow::Result;

#[automock]
trait ExchangeRateService {
    fn get_rate(&self, from_currency: &str, to_currency: &str) -> Result<f64>;
}

struct PricingService {
    exchange_rate_service: Box<dyn ExchangeRateService>,
}

impl PricingService {
    fn convert_price(&self, amount: f64, from_currency: &str, to_currency: &str) -> Result<f64> {
        let rate = self.exchange_rate_service.get_rate(from_currency, to_currency)?;
        Ok(amount * rate)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    
    #[test]
    fn test_convert_price_should_use_exchange_rate() -> Result<()> {
        let mut mock_service = MockExchangeRateService::new();
        
        // Mock out the result
        mock_service.expect_get_rate()
            .with(eq("USD"), eq("EUR"))
            .returning(|_, _| Ok(1.5));
        
        let pricing_service = PricingService {
            exchange_rate_service: Box::new(mock_service),
        };

        // Act
        let result = pricing_service.convert_price(100.0, "USD", "EUR")?;

        // Assert
        assert_eq!(150.0, result);
        Ok(())
    }
}

In this structure:

  • We define an ExchangeRateService trait.
  • MockExchangeRateService is created using the mockall crate, allowing us to fake behavior without implementing actual logic.
  • expect_get_rate() sets up the expectation and return value for the method.
Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal