Skip to content
This repository has been archived by the owner on May 16, 2020. It is now read-only.

Extension for both RhinoMocks and Moq - Create Mocks from an Instance of an Interface

License

Notifications You must be signed in to change notification settings

SkyKick/RhinoMoq.FromInstance

Repository files navigation

RhinoMoq.FromInstance

Extension for both RhinoMocks and Moq - Create Mocks from an Instance of an Interface

What It Does:

This extension solves the problem of generating a mock from an existing instance. This is handy when you are testing a class Foo that has a dependency on a complex object Bar and you want some of Bar's members to be mocked and the remaining to execute against the original member.

In other words, this saves you from intializing every member.

Example

Given an Interface and Implementation

public interface IFoo 
{
    string StringProp { get; }

    int IntProp { get; }
}

public class Foo : IFoo
{
    public string StringProp { get; set; }
    public int IntProp { get; set; }
}
Moq:
var mock = 
    new Mock<IFoo>()
        .SetupFromInstance(new Foo
        {
            StringProp = "Actual",
            IntProp = 42
        });

//mock a method
mock
    .Setup(x => x.IntProp).Returns(25);

//mock works
Assert.Equal(
    25,
    mock.Object.IntProp);

//original property works
Assert.Equal(
    "Actual",
    mock.Object.StringProp);
Rhino Mocks:
var mock = MockRepository.GenerateMock<IFoo>();

//mock a method
mock
    .Stub(x => x.IntProp)
    .Do(new Func<int>(() => 25));

//stub the rest from instance
mock
    .StubFromInstance(new Foo
    {
        StringProp = "Actual",
        IntProp = 42
    });

//mock works
Assert.AreEqual(
    25,
    mock.IntProp);

//original property works
Assert.AreEqual(
    "Actual",
    mock.StringProp);

Is This Different From an AutoMocker?

Yes. AutoMocker will create a default mock of all dependencies, but will not initialize the mocks. But AutoMockers and FromInstance will play nice together.

About

Extension for both RhinoMocks and Moq - Create Mocks from an Instance of an Interface

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages