Skip to content

Usage Cheatsheet

Robert Coltheart edited this page May 8, 2019 · 6 revisions

Choose one flavor of mocks to use

Specify a subject under test

class When_using_a_car : WithSubject<Car>
{
    Because of = () =>
        Subject.StartCar();
}

Mocking an interface

class When_using_a_car : WithSubject<Car>
{
    static bool engine_off;

    Establish context = () =>
        The<IEngine>()
            .WhenToldTo(x => x.TurnOff(Param.IsAny<MethodUsed>()))
            .Return(true);

    Because of = () =>
        engine_off = Subject.StopCar();

    It should_turn_off_engine = () =>
        engine_off.ShouldBeTrue();
}

Throw an exception when a mocked method is called

Establish context = () =>
    The<IEngine>()
        .WhenToldTo(x => x.TurnOff(Param.IsAny<MethodUsed>()))
        .Throw(new InvalidOperationException());

Verify a method is called on a mock

It should_turn_off_engine_once = () =>
    The<IEngine>()
        .WasToldTo(x => x.TurnOff(Param.IsAny<MethodUsed>()))
        .OnlyOnce();

Verify a method is never called on a mock

It should_turn_off_engine_once = () =>
    The<IEngine>()
        .WasNotToldTo(x => x.TurnOff(Param.IsAny<MethodUsed>()));

Configure an auto-mocked interface for a subject

public class Car
{
    public Car(IEngine engine)
    {
    }
}

class When_using_a_car : WithSubject<Car>
{
    Establish context = () =>
        Configure(x => x.For<IEngine>().Use<RotaryEngine>());
}

Intercept arguments passed to a mocked method

Only works on void return methods.

Establish context = () =>
    The<IEngine>()
        .WhenToldTo(x => x.Service(Param.IsAny<bool>(), Param.IsAny<int>()))
        .Callback<bool, int>((x, y) =>
        {
            is_full_service = x;
            tires_count = y;
        });

Mock 'out' and 'ref' parameters

Only works on void return methods.

Establish context = () =>
{
    bool changed;
            
    The<IEngine>()
        .WhenToldTo(x => x.ChangeTire(1, out changed))
        .AssignOutAndRefParameters(true);
};

In the above changed will be set to true.

Clone this wiki locally

⌂ 换网址