Mock.mockMethod

Replace a method in the mock object by adding a mock method to be called in its place. By default parent methods are called in lieu of any replacements unless parent methods are disabled.

class Mock(C)
void
mockMethod
(
T
)
(
string name
,,
ulong minimumCount = 0
,
ulong maximumCount = ulong.max
,
string file = __FILE__
,
size_t line = __LINE__
)
if (
is(C == class) ||
is(C == interface)
)

Parameters

name
Type: string

The name of the method to replace. (Only the name should be used, no parameters, etc.)

delegate_
Type: T

The delegate to be used instead of calling the original method. The delegate must have the exact signature of the method being replaced.

minimumCount
Type: ulong

The minimum amount of times this method must be called when asserting calls.

maximumCount
Type: ulong

The maximum amount of times this method must be called when asserting calls.

file
Type: string

The file name where the error occurred. The value is added automatically at the call site.

line
Type: size_t

The line where the error occurred. The value is added automatically at the call site.

Throws

DUnitAssertError if the passed delegate does not match the signature of any overload of the method named.

Caveats:

  1. In the case of replacing overloaded methods the delegate signature defines which method to replace. Helpful errors will be raised on non matching signatures.
  2. Templated methods are final by default and therefore cannot be mocked.

Examples

1 import dunit.mockable;
2 
3 class T
4 {
5    int getValue()
6    {
7        return 1;
8    }
9 
10    mixin Mockable!(T);
11 }
12 
13 unittest
14 {
15    import dunit.toolkit;
16 
17    auto mock = T.getMock();
18 
19    // Replace the 'getValue' method.
20    mock.mockMethod("getValue", delegate(){
21        return 2;
22    });
23 
24    mock.getValue().assertEqual(2);
25 }

See Also

Meta