Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I copy a Moq Mock implementation?

I've been using Moq and loving it, but I've come across a problem mocking some legacy code (before I try to refactor it away)

What I really want to do is have two separate mocks, with only slightly different implementation, such as the sample below.

        Mock<IFoo> fooMock = new Mock<IFoo>();
        fooMock.SetupGet(f => f.bar).Returns(7);
        fooMock.SetupGet(f => f.bar2).Returns(3);
        Mock<IFoo> fooMockClone = new Mock<IFoo>(fooMock.Behavior);
        fooMockClone.SetupGet(f => f.bar).Returns(9);

        Debug.Assert(7 == fooMock.Object.bar);
        Debug.Assert(9 == fooMockClone.Object.bar);
        Debug.Assert(3 == fooMockClone.Object.bar2);
        Debug.Assert(3 == fooMock.Object.bar2);

This is a simple example but the real code is an object with dozens of methods and I want slightly different implementation for two versions.

Thanks

like image 578
Chris Williams Avatar asked Nov 10 '22 01:11

Chris Williams


1 Answers

I wonder in this case then if you're looking for Behavior tests. Here's a sample in Machine.Fakes with the Moq sublayer ... it allows for the nesting it seems like you're wanting, while still maintaining logical separation of the tests. Requires NuGet packages: Machine.Fakes.Moq, Machine.Specifications.Should

class IFoo_test_context : WithSubject<IFoo>
{
    Establish context = () => Subject.bar2 = 3;
}

class When_fooing_with_seven : IFoo_test_context
{
    Establish context = () => Subject.bar = 7;

    It bar_should_be_seven =()=> Subject.bar.ShouldEqual(7);
    It bar2_should_be_three =()=> Subject.bar.ShouldEqual(3);
}

class When_fooing_with_nine : IFoo_test_context
{
    Establish context = () => Subject.bar = 9;

    It bar_should_be_nine = () => Subject.bar.ShouldEqual(9);
    It bar2_should_be_three = () => Subject.bar.ShouldEqual(3);
}

Again the example is somewhat silly because it's testing the mocking behavior, but it's hard to see what you're ultimately trying to accomplish. There is no copy constructor in the way you want with Mock as far as I can tell.

like image 115
Bryan Boettcher Avatar answered Nov 15 '22 07:11

Bryan Boettcher