Struct unimock::build::DefineResponse

source ·
pub struct DefineResponse<'p, F: MockFn, O: Ordering> { /* private fields */ }
Expand description

A matched call pattern, ready for defining a single response.

Implementations§

source§

impl<'p, F: MockFn, O: Ordering> DefineResponse<'p, F, O>

source

pub fn returns<T>(self, value: T) -> QuantifyReturnValue<'p, F, T, O>
where T: IntoReturnOnce<F::OutputKind>, <<F as MockFn>::OutputKind as Kind>::Return: IntoReturner<F>,

Specify the output of the call pattern by providing a value. The output type cannot contain non-static references. It must also be Send and Sync because unimock needs to store it.

The value can be anything that can be converted Into the mock function output.

Unless explicitly configured on the returned QuantifyReturnValue, the return value specified here can be returned only once, because this method does not require a Clone bound. To be able to return this value multiple times, quantify it explicitly.

§Example

Using returns(&str) for a method that outputs String:

#[unimock(api=TraitMock)]
trait Trait {
    fn func(&self) -> String;
}

let u = Unimock::new(
    TraitMock::func
        .next_call(matching!())
        .returns("hello")
);

assert_eq!("hello", u.func());
source§

impl<'p, F, O> DefineResponse<'p, F, O>
where F: MockFn, O: Ordering,

source

pub fn returns_default(self) -> Quantify<'p, F, O>
where F::OutputKind: Return, <F::OutputKind as Return>::Type: ReturnDefault<F::OutputKind>, <<F as MockFn>::OutputKind as Kind>::Return: IntoReturner<F>,

Specify the response of the call pattern by calling Default::default().

§Example
#[unimock(api=TraitMock)]
trait Trait {
    fn get(&self) -> Option<String>;
}

let u = Unimock::new(
    TraitMock::get
        .next_call(matching!())
        .returns_default()
);

assert_eq!(None, u.get());
source

pub fn answers(self, answer_fn: &'static F::AnswerFn) -> Quantify<'p, F, O>

Specify the response of the call pattern by applying the given function that can then compute it based on input parameters.

The applied function can respond with types that don’t implement Send and Sync.

The function signature has the same signature as the trait function that it mocks, including self. The self argument is included because of a potential need for calling .e.g. make_ref on it.

§Example
use std::cell::Cell;

#[unimock(api=TraitMock)]
trait Trait {
    fn get_cell(&self, input: i32) -> Cell<i32>;
}

let u = Unimock::new(
    TraitMock::get_cell
        .next_call(matching!(84))
        .answers(&|_, input| Cell::new(input / 2))
);

assert_eq!(Cell::new(42), u.get_cell(84));
§Parameter mutation
use std::cell::Cell;

#[unimock(api=TraitMock)]
trait Trait {
    fn mutate(&self, input: &mut i32);
}

let u = Unimock::new(
    TraitMock::mutate
        .next_call(matching!(41))
        .answers(&|_, input| {
            *input += 1;
        })
);

let mut number = 41;
u.mutate(&mut number);
assert_eq!(number, 42);
§Borrow from self
#[unimock(api=TraitMock)]
trait Trait {
    fn get(&self) -> &u32;
}

let u = Unimock::new(
    TraitMock::get
        .next_call(matching!())
        .answers(&|u| u.make_ref(42))
);

assert_eq!(u.get(), &42);
§Recursion
#[unimock(api=FibMock)]
trait Fib {
    fn fib(&self, input: i32) -> i32;
}

let u = Unimock::new((
    FibMock::fib
        .each_call(matching!(1 | 2))
        .returns(1),
    FibMock::fib
        .each_call(matching!(_))
        .answers(&|u, input| {
            u.fib(input - 1) + u.fib(input - 2)
        })
));

assert_eq!(55, u.fib(10));
source

pub fn answers_arc(self, answer_fn: Arc<F::AnswerFn>) -> Quantify<'p, F, O>

Specify the response of the call pattern by invoking the given closure that can then compute it based on input parameters.

use std::sync::{Arc, Mutex};

#[unimock(api=TraitMock)]
trait Trait {
    fn get(&self) -> i32;
}

let mutex: Arc<Mutex<i32>> = Arc::new(Mutex::new(0));

let u = Unimock::new(
    TraitMock::get
        .each_call(matching!())
        .answers_arc({
            let mutex = mutex.clone();
            Arc::new(move |_| {
                *mutex.lock().unwrap()
            })
        })
);

assert_eq!(0, u.get());
*mutex.lock().unwrap() = 42;
assert_eq!(42, u.get());
source

pub fn panics(self, message: impl Into<String>) -> Quantify<'p, F, O>

Prevent this call pattern from succeeding by explicitly panicking with a custom message.

source

pub fn applies_unmocked(self) -> Quantify<'p, F, O>

Instruct this call pattern to invoke its corresponding unmocked function.

For this to work, the mocked trait must be configured with an unmock_with=[..] parameter. If unimock doesn’t find a way to unmock the function, this will panic when the function is called.

#[unimock(api=FibMock, unmock_with=[my_fibonacci])]
trait Fib {
    fn fib(&self, input: i32) -> i32;
}

// note: no recursion guard:
fn my_fibonacci(f: &impl Fib, input: i32) -> i32 {
    f.fib(input - 1) + f.fib(input - 2)
}

let u = Unimock::new((
    FibMock::fib
        .each_call(matching!(1 | 2))
        .returns(1),
    FibMock::fib
        .each_call(matching!(_))
        .applies_unmocked()
));

assert_eq!(55, u.fib(10));
source

pub fn applies_default_impl(self) -> Quantify<'p, F, O>

Instruct this call pattern to invoke the method’s default implementation.

If the method has no default implementation, the method will panic when called.

It is not required to pre-register calls to a default-implemented methods like this, but it’s useful for verifying that they are in fact called.

§Example
#[unimock(api=TraitMock)]
trait Trait {
    fn required(&self, input: i32) -> i32;
    fn provided(&self) -> i32 {
        self.required(0)
    }
}

let u = Unimock::new((
    TraitMock::provided
        .next_call(matching!())
        .applies_default_impl(),
    // the above call delegates to the required method:
    TraitMock::required
        .next_call(matching!(0))
        .returns(42)
));

assert_eq!(42, u.provided());

Auto Trait Implementations§

§

impl<'p, F, O> Freeze for DefineResponse<'p, F, O>
where O: Freeze,

§

impl<'p, F, O> !RefUnwindSafe for DefineResponse<'p, F, O>

§

impl<'p, F, O> Send for DefineResponse<'p, F, O>
where O: Send, F: Send,

§

impl<'p, F, O> Sync for DefineResponse<'p, F, O>
where O: Sync, F: Sync,

§

impl<'p, F, O> Unpin for DefineResponse<'p, F, O>
where O: Unpin, F: Unpin,

§

impl<'p, F, O> !UnwindSafe for DefineResponse<'p, F, O>

Blanket Implementations§

source§

impl<T> Any for T
where T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

impl<T, U> Into<U> for T
where U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

source§

impl<T> Is for T
where T: ?Sized,

§

type EqTo = T

source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.