ameniameni / moq

Automatically exported from code.google.com/p/moq
Other
0 stars 0 forks source link

Should consider using IDisposable to call Verify #220

Closed GoogleCodeExporter closed 8 years ago

GoogleCodeExporter commented 8 years ago
What steps will reproduce the problem?

var x = new Mock<X>();

x
    .Setup()
    .Verifiable();

// Lots of code

x.Verify();

What do you want to see instead?

using (x = new Mock<X>())
{
    x
        .Setup()
        .Verifiable();

    // Lots of code
}

What version of the product are you using? On what operating system?

Moq 4.0.812.4 W7RC VS2K8

Original issue reported on code.google.com by bartel...@gmail.com on 12 Nov 2009 at 4:57

GoogleCodeExporter commented 8 years ago
Have a temp workaround:-

    public static class MockExtensions
    {
        public IDisposable Verifier( this Mock mock )
        {
            return new UndoSetupAction( (  ) => mock.Verify(  ) );
        }
    }

    public class UndoSetupAction : IDisposable
    {
        public delegate void RollbackActionDelegate();
        private RollbackActionDelegate _action;
        public UndoSetupAction( RollbackActionDelegate action )
        {
            _action = action;
        }

        void IDisposable.Dispose()
        {
            _action();
            _action = null;
        }
    }

Hence I can now write:

x = new Mock<X>();
using (x.Verifier())
{
    x
        .Setup()
        .Verifiable();

    // Lots of code
}

Original comment by bartel...@gmail.com on 12 Nov 2009 at 5:04

GoogleCodeExporter commented 8 years ago
We have decided long ago that this leads to imposible to reuse mocks, as well 
as too 
coarse-grained error messages as you then have to figure out which of a number 
of 
mocks failed (using a mock repository, as nested usings on multiple mocks also 
gets 
very cumbersome very quickly).

And many users reported this being ugly in Rhino too.

Once you switch to the AAA style of mocking (calling Verify(expression) instead 
of 
using Verifiable() setups), you'll see that this makes little sense.

Original comment by kzu.net on 12 Nov 2009 at 6:50

GoogleCodeExporter commented 8 years ago
Doh!

Thanks for the correction. Have recoded usages of this approach and they're 
much 
clearer, thanks.

Any chance of there being a Core vs Ext split and/or approach a la xUnit.net 
with an 
agressive trimming of the Core, possibly via extension classes to make 
Verifiable
() 'Obsolete' ? Maybe something like 
http://briannoyes.net/2009/11/04/UseExtensionMethodsToPhaseOutABadAPI.aspx ?

Original comment by bartel...@gmail.com on 13 Nov 2009 at 11:09