Mockall: how to return a mocked struct from another one

⚓ Rust    📅 2026-06-09    👤 surdeus    👁️ 1      

surdeus

I'm trying to create a wrapper around windows-service's API to mock it with mockall.

My code looks like this:
I have a WindowsServiceManagerProvider that I use to obtain a WindowsServiceManager that I can use to obtain WindowsService.

use mockall::automock;
use windows_service::{
    service::{ServiceAccess, ServiceInfo},
    service_manager::ServiceManagerAccess,
};

/* -------------------------------------------------------------------------- */

pub struct WindowsServiceManagerProvider;

#[automock]
impl WindowsServiceManagerProvider {
    pub fn get_local(
        request_access: ServiceManagerAccess,
    ) -> anyhow::Result<WindowsServiceManager> {
        todo!();
    }
}

/* -------------------------------------------------------------------------- */

pub struct WindowsServiceManager(windows_service::service_manager::ServiceManager);

#[automock]
impl WindowsServiceManager {
    pub fn open_service(
        &self,
        name: &str,
        request_access: ServiceAccess,
    ) -> anyhow::Result<WindowsService> {
        todo!();
    }

    pub fn create_service(
        &self,
        service_info: &ServiceInfo,
        service_access: ServiceAccess,
    ) -> anyhow::Result<WindowsService> {
        todo!();
    }
}

/* -------------------------------------------------------------------------- */

pub struct WindowsService(windows_service::service::Service);

#[automock]
impl WindowsService {
    pub fn start(&self) -> anyhow::Result<()> {
        todo!();
    }

    pub fn stop(&self) -> anyhow::Result<()> {
        todo!();
    }

    pub fn delete(&self) -> anyhow::Result<()> {
        todo!();
    }
}

/* -------------------------------------------------------------------------- */

The problem rises when I'm trying to mock WindowsServiceManager:

#[test]
fn test() {
    let mut service_manager = WindowsServiceManager::new();
    service_manager.expect_open_service()
        .returning(|_, _| {
            Ok( /* what's here? */ )
        });
}

returning requires that I'm returning a WindowsService, but I want to returns a MockWindowsService instead.

So my question is how I can achieve such "nested" mocked structs with mockall? Is this even possible?

2 posts - 1 participant

Read full topic

🏷️ Rust_feed