Use the crate mockall to mock the email service in integration tests

This commit is contained in:
Greg Burri 2025-05-02 13:38:41 +02:00
parent 3626f8a11b
commit 8c70f90234
5 changed files with 109 additions and 23 deletions

View file

@ -1,23 +1,20 @@
use std::sync::Arc;
use recipes::email;
use async_trait::async_trait;
use mockall::{mock, predicate::*};
pub struct MockEmailService;
use crate::email;
impl MockEmailService {
pub fn create_service() -> Arc<dyn email::EmailServiceTrait> {
Arc::new(Self {})
mock! {
pub EmailService {}
#[async_trait]
impl email::EmailServiceTrait for EmailService {
async fn send_email(&self, email: &str, title: &str, message: &str)
-> Result<(), email::Error>;
}
}
#[async_trait::async_trait]
impl email::EmailServiceTrait for MockEmailService {
async fn send_email(
&self,
_email: &str,
_title: &str,
_message: &str,
) -> Result<(), email::Error> {
Ok(())
}
// Default email service: will crash if `send_email` method is called.
pub fn new_mock_email_service() -> Arc<dyn email::EmailServiceTrait> {
Arc::new(MockEmailService::new())
}

View file

@ -1,10 +1,16 @@
use std::error::Error;
use std::{error::Error, sync::Arc};
use recipes::{app, config, data::db, log};
use recipes::{app, config, data::db, email, log};
mod mock_email;
pub mod mock_email;
pub async fn common_state() -> Result<app::AppState, Box<dyn Error>> {
common_state_with_email_service(mock_email::new_mock_email_service()).await
}
pub async fn common_state_with_email_service(
email_service: Arc<dyn email::EmailServiceTrait>,
) -> Result<app::AppState, Box<dyn Error>> {
let db_connection = db::Connection::new_in_memory().await?;
let config = config::Config::default();
let log = log::Log::new_no_log();
@ -12,7 +18,7 @@ pub async fn common_state() -> Result<app::AppState, Box<dyn Error>> {
config,
db_connection,
log,
email_service: mock_email::MockEmailService::create_service(),
email_service,
})
}