Giter Site home page Giter Site logo

moq-sequences's People

Contributors

dwhelan avatar jtone123 avatar stakx avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

moq-sequences's Issues

This library no longer works with the latest version of Moq

Steps to reproduce:

  • Install the latest version of Moq.Sequences (2.1.0) and Moq (4.11.0).

  • Run the following program against the above libraries:

    public interface IFoo
    {
        void Do(int arg);
    }
    
    var mock = new Mock<IFoo>();
    using (Sequence.Create())
    {
        mock.Setup(m => m.Do(1)).InSequence();
        mock.Setup(m => m.Do(2)).InSequence();
        mock.Setup(m => m.Do(3)).InSequence();
    }

Expected behavior:

The program throws a sequence exception because the sequence wasn't completed.

Actual behavior:

System.Reflection.TargetParameterCountException: Parameter count mismatch.
   at System.Reflection.RuntimeMethodInfo.InvokeArgumentsCheck(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
   at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
   at Moq.Sequences.Step.GetFailureMessage(String failMessage)
   at Moq.Sequences.Step.EnsureComplete(String context)
   at Moq.Sequences.Loop.<>c__DisplayClass14_0.<EnsureComplete>b__0(Step step)
   at System.Collections.Generic.List`1.ForEach(Action`1 action)
   at Moq.Sequences.Loop.EnsureComplete(String context)
   at Moq.Sequences.Sequence.DoDisposalChecks()
   at Moq.Sequences.Loop.Dispose()
   at Program.Main()

Notes:

This is due to changes in the implementation of Moq's internal method Times.GetExceptionMessage which Moq.Sequences calls via reflection.

Dependency to NUnit ?

I noticed that the library itself doesn't require NUnit.
But the NuGet package has dependency to NUnit, because of included unit-tests.

This is not good.

What if to remove the unit-tests into a separated project and exclude them from the NuGet package (as well as the dependency to NUnit) ?

Sequence at verification?

Hi,

I'm looking at the readme doc, and it seems the way it works is at setup.
I'm wondering if I could also go like:

/*******/

// assert
using (Sequence.Create())
{
  _TenantServiceMock
    .Verify(tenantService => tenantService.FindTenantAsync(subdomain),
      Times.Once);

  _GlobalDbContextTransactionFactoryMock
    .Verify(globalTransactionFactory => globalTransactionFactory.BeginTransactionAsync(),
      Times.Once);

  _PerTenantDbContextTransactionFactoryMock
    .Verify(perTenantTransactionFactory => perTenantTransactionFactory.BeginTransactionAsync(),
      Times.Once);

  _PerTenantUserStoreMock
    .Verify(perTenantUserStore => perTenantUserStore.CreateAsync(perTenantUser, defaultCancellationToken),
      Times.Once);

  _TenantStoreMock
    .Verify(tenantUserStore =>
      tenantUserStore
        .CreateAsync(It.Is<Tenant>(updatedTenant =>
          updatedTenant == tenant
          && updatedTenant.IsInitialized == true), defaultCancellationToken),
      Times.Once);

  globalTransactionMock
    .Verify(globalTransaction => globalTransaction.CommitAsync(defaultCancellationToken),
      Times.Once);

  perTenantTransactionMock
    .Verify(perTenantTransaction => perTenantTransaction.CommitAsync(defaultCancellationToken),
      Times.Once);

  globalTransactionMock
    .Verify(globalTransaction => globalTransaction.DisposeAsync(),
      Times.Once);

  perTenantTransactionMock
    .Verify(perTenantTransaction => perTenantTransaction.DisposeAsync(),
      Times.Once);
}
 
VerifyNoOtherCalls();

Doesn't detect method call, when callback is added.

When added callback in Mock.Setup verifying of sequence is fail.
I looked to source code and noticed that AddStep adds Callback and when we pass Action to ISetup.Callback it overrides old one so after calling mock method Serquence.Record() doesn't call and EnsureComplete is fail.

Doesn't detect excess calls

The sequence should define that for a given mock object, these and only these calls should occur. Unfortunately, that behavior isn't fullfilled. Excess calls to the mock (eg, when the sequence has completed), cause no assertions in either Moq.Sequence or in VerifyAll().

License

Hi,

Thanks for the project. One question: which is the license for the source code? Can I use the compiled dll in a comercial project?

Thanks,
Pescuma

Call the same method twice in a sequence fails

I'm trying to do this:

using (Sequence.Create())
{
    mock.Setup(_ => _.Method1()).InSequence();
    mock.Setup(_ => _.Method2()).InSequence();
    mock.Setup(_ => _.Method1()).InSequence();
}

And it fails in the first method call. I tried to debug and seems like the problem is that it "sees" the second Method1 call when it is called for the first time.

Exceptions are swallowed/obscured

In a simple usage like this:

var mock = new Mock<Something>();
using (Sequence.Create())
{
    mock.Setup(m => m.Method1()).InSequence();
    mock.Setup(m => m.Method2()).InSequence();
    mock.DoStuff();
}

If an exception is thrown from the DoStuff() method, the test will fail but with a sequence exception, hiding the actual exception from DoStuff(). It makes troubleshooting such tests very difficult. Basically I've had to comment-out all the Moq.Sequences stuff in order to get to the actual error.

NuGet package

First of all, thanks for sharing this nifty peace of code. :)
It would be even more awesome if you could publish it as a nuget package.

Cheers,
Julian

Moq version 4.1.1309.1617

I'm currently using Moq version 4.1.1309.1617
In order to get it working I added this assemblyBinding in my app.config file

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="Moq" publicKeyToken="69f491c39445e920" />
        <bindingRedirect oldVersion="4.0.10827.0" newVersion="4.1.1309.1617" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
</configuration>

nuget - nunit reference

Hi Declan,

This looks very cool.

What I don't like about the nuget package, is that it also pulls in a reference to nUnit.

Imo you should split the production code and the test code into two projects/assemblies and only package the production assembly. My guess is that people who simply want to use your package will almost never run the supplied tests.

Whereas people who run the tests, will most likely get the source code anyway.

Cheers,
Markus

Replace Moq.Sequence's use of reflection to extract Times' internal fields.

Moq.Sequences is built on top of two mechanisms:

  1. Hooking into mocks using .Callback() to be notified of invocations, so that immediate checking can be performed. (Which causes #10 btw.)

  2. Using reflection to extract Times' private fields from and to. Checks are run against those.

Moq's internals could change at any time, so relying on those obviously means that Moq.Sequences is in danger of breaking, potentially irreversibly—Moq's #350 would have that effect, if merged.

An alternative for this fragile approach should be found. Some options:

  1. Find a new way to interact with Times via its public API surface. This appears to be currently impossible since Times appears as a completely opaque type outside the Moq library. Perhaps use inspectable LINQ expression trees (Expression<Func<Times>>). Or file an issue with Moq to make Times more transparent?

  2. Otherwise, if the implementation of Moq's Times indeed changes (i.e. the from and to fields go away), modify Moq.Sequence's package metadata to reflect that it is not compatible with newer versions of Moq.

  3. Render Moq.Sequences obsolete by incorporating the same functionality into Moq itself. There has been at least one attempts at something similar; see e.g. Moq's #21 and #130.

How to use sequence when testing async methods?

I am having trouble with testing async methods.
When I do this:

[Test]
public async Task Demo()
{
    using (Sequence.Create())
    {        
        _fooMock.Setup(f => f.Fooxiate()).InSequence();

        _barMock.Setup(b => b.Baronize()).InSequence();

        var result = await _cut.DoMyStuffAsync();

        Assert.AreEqual("someString", result);
    }
}

The I get an exception in the production code when calling _foo.Fooxiate() saying:

Moq.Sequences.SequenceUsageException: 'Mock invocation can only be called with an active MockSequence created with MockSequence.Create()

Am I doing something wrong or is testing of call sequence in async methods not supported?

Here is the full demo code including the above mentioned production code:

using System.Threading.Tasks;
using Moq;
using Moq.Sequences;
using NUnit.Framework;

namespace TestingAsync.Tests
{
    [TestFixture]
    public class SomeClassTests
    {
        private SomeClass _cut;

        private Mock<IFoo> _fooMock;
        private Mock<IBar> _barMock;

        [SetUp]
        public void Setup()
        {
            _fooMock = new Mock<IFoo>();
            _barMock = new Mock<IBar>();

            _cut = new SomeClass(_fooMock.Object, _barMock.Object);
        }

        [Test]
        public async Task Demo()
        {
            using (Sequence.Create())
            {
                _fooMock.Setup(f => f.Fooxiate()).InSequence();

                _barMock.Setup(b => b.Baronize()).InSequence();

                var result = await _cut.DoMyStuffAsync();

                Assert.AreEqual("someString", result);
            }
        }
    }

    public class SomeClass
    {
        private readonly IFoo _foo;
        private readonly IBar _bar;

        public SomeClass(IFoo foo, IBar bar)
        {
            _bar = bar;
            _foo = foo;
        }

        public async Task<string> DoMyStuffAsync()
        {
            return await Task.Run(() => DoMyStuff());
        }

        private string DoMyStuff()
        {
            _foo.Fooxiate();

            _bar.Baronize();

            return "someString";
        }
    }

    public interface IBar
    {
        void Baronize();
    }

    public interface IFoo
    {
        void Fooxiate();
    }
}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.