An example rust library that easily mocks an interface for unit testing with the
mockall
crate.
An important Application
method cool_algorithm
needs to be unit tested.
cool_algorithm
relies on an external service and for whatever reason, that external service cannot
be used during unit testing.
To remedy this, we define the I32Calculator
trait:
Lines 74 to 83 in 8e6303e
And implement it for external service's client ExternalI32Calculator
:
Lines 89 to 105 in 8e6303e
We then declare an i32_calculator
field in our Application
that is I32Calculator
:
Lines 109 to 111 in 8e6303e
To enable mocking of I32Calculator
, we add the #[cfg_attr(test, mockall::automock)]
attribute to
the trait's definition:
Lines 73 to 74 in 8e6303e
In our unit test, we then create a mock object that is I32Calculator
and set up expectations and
return values for the methods will be called during the cool_algorithm
call:
Lines 129 to 174 in 8e6303e