dwhelan / moq-sequences Goto Github PK
View Code? Open in Web Editor NEWEnforce that method calls are done in a specified sequence
Home Page: dpwhelan.com/moq.sequences
License: MIT License
Enforce that method calls are done in a specified sequence
Home Page: dpwhelan.com/moq.sequences
License: MIT License
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.
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) ?
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()
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();
}
}
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();
}
The program throws a sequence exception because the sequence wasn't completed.
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()
This is due to changes in the implementation of Moq's internal method Times.GetExceptionMessage
which Moq.Sequences calls via reflection.
The homepage URL mentioned next to the GitHub repository description (http://dpwhelan.com/moq.sequences) appears to be broken and should probably be updated or removed.
/cc @dwhelan
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
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.
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().
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.
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
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
Moq.Sequences is built on top of two mechanisms:
Hooking into mocks using .Callback()
to be notified of invocations, so that immediate checking can be performed. (Which causes #10 btw.)
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:
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?
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.
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.
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();
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>
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.