test_double
A set of procedural macros that can swap in mock objects, dummy objects, or other test doubles only when testing.
This doesn't solve the problem of mocking in the first place, which is worth looking into, but it does allow you to import mock objects into your tests easily.
To use, add the following to your Cargo.toml
:
[]
= "0.3.0"
Note that this crate has not yet reached version 1.0, so the API may change between releases.
Substituting A Single Use Statement
#[test_double]
can be used to substitute one type for another when testing:
use Database;
// Expands to:
use Database;
use DatabaseMock as Database;
The substituted type name defaults to the original name, with Mock
appended to it.
Alternate Name
You can also provide an alternate name to be substituted instead:
use Database;
// Expands to:
use Database;
use DummyDB as Database;
Note that this is only supported when substituting a single type name.
Prefixed
As a shortcut, if you would like to use the original type name, prefixed with Mock
instead of appended, you can use the #[test_double_prefixed]
macro:
use Database;
// Expands to:
use Database;
use MockDatabase as Database;
Grouped Imports
It's worth noting that these macros also support grouped imports:
use ;
// Expands to:
use Database;
use DatabaseMock as Database;
use Connection;
use ConnectionMock as Connection;
Limitations
For #[test_doubles]
and #[test_doubles_prefixed]
:
- Glob imports, such as
use blah::*;
, are not supported - When providing an alternate substituted name, grouped imports, such as
use blah::{foo, bar};
, are not supported
Substituting Multiple Use Statements
If you'd like to substitute multiple use statements at once, you can use the test_doubles!
macro. Note that this macro does not support using an alternate substituted name, but it does support grouped imports, such as use blah::{foo, bar};
.
test_doubles!
// Expands to:
use Database;
use DatabaseMock as Database;
use Connection;
use ConnectionMock as Connection;
use ImageCache;
use ImageCacheMock as ImageCache;
Prefixed
Similar to the single-use-statement macros, there is a test_doubles_prefixed!
macro that can prefix instead of appending:
test_doubles_prefixed!
// Expands to:
use Database;
use MockDatabase as Database;
use ImageCache;
use MockImageCache as ImageCache;
Limitations
For test_doubles!
and test_doubles_prefixed!
:
- Glob imports, such as
use blah::*;
, are not supported