Giter Site home page Giter Site logo

moq4's Introduction

moq

Version Downloads Discord Chat Sponsors

The most popular and friendly mocking library for .NET

  var mock = new Mock<ILoveThisLibrary>();

  // WOW! No record/replay weirdness?! :)
  mock.Setup(library => library.DownloadExists("2.0.0.0"))
      .Returns(true);

  // Use the Object property on the mock to get a reference to the object
  // implementing ILoveThisLibrary, and then exercise it by calling
  // methods on it
  ILoveThisLibrary lovable = mock.Object;
  bool download = lovable.DownloadExists("2.0.0.0");

  // Verify that the given method was indeed called with the expected value at most once
  mock.Verify(library => library.DownloadExists("2.0.0.0"), Times.AtMostOnce());

Moq also is the first and only library so far to provide Linq to Mocks, so that the same behavior above can be achieved much more succinctly:

  ILoveThisLibrary lovable = Mock.Of<ILoveThisLibrary>(l =>
    l.DownloadExists("2.0.0.0") == true);

  // Exercise the instance returned by Mock.Of by calling methods on it...
  bool download = lovable.DownloadExists("2.0.0.0");

  // Simply assert the returned state:
  Assert.True(download);
  
  // If you want to go beyond state testing and want to 
  // verify the mock interaction instead...
  Mock.Get(lovable).Verify(library => library.DownloadExists("2.0.0.0"));

You can think of Linq to Mocks as "from the universe of mocks, give me one whose behavior matches this expression".

Check out the Quickstart for more examples!

What?

Moq (pronounced "Mock-you" or just "Mock") is the only mocking library for .NET developed from scratch to take full advantage of .NET Linq expression trees and lambda expressions, which makes it the most productive, type-safe and refactoring-friendly mocking library available. And it supports mocking interfaces as well as classes. Its API is extremely simple and straightforward, and doesn't require any prior knowledge or experience with mocking concepts.

Why?

The library was created mainly for developers who aren't currently using any mocking library (or are displeased with the complexities of some other implementation), and who are typically manually writing their own mocks (with more or less "fanciness"). Most developers in this situation also happen to be quite pragmatic and adhere to state (or classic) TDD. It's the result of feeling that the barrier of entry from other mocking libraries is a bit high, and a simpler, more lightweight and elegant approach is possible. Moq achieves all this by taking full advantage of the elegant and compact C# and VB language features collectively known as LINQ (they are not just for queries, as the acronym implies).

Moq is designed to be a very practical, unobtrusive and straight-forward way to quickly setup dependencies for your tests. Its API design helps even novice users to fall in the "pit of success" and avoid most common misuses/abuses of mocking.

When it was conceived, it was the only mocking library that went against the generalized and somewhat unintuitive (especially for novices) Record/Replay approach from all other libraries (and that might have been a good thing ;)).

Not using Record/Replay also means that it's straightforward to move common expectations to a fixture setup method and even override those expectations when needed in a specific unit test.

You can read more about the "why" and see some nice screenshots at kzu's blog.

Where?

See our Quickstart examples to get a feeling of the extremely simple API and install from NuGet.

Read about the announcement at kzu's blog. Get some background on the state of mock libraries from Scott Hanselman.

In-depth documentation is being added to the documentation website.

Who?

Moq was originally developed by Clarius, Manas and InSTEDD.

Moq uses Castle DynamicProxy internally as the interception mechanism to enable mocking.

Features at a glance

Moq offers the following features:

  • Strong-typed: no strings for expectations, no object-typed return values or constraints
  • Unsurpassed VS IntelliSense integration: everything supports full VS IntelliSense, from setting expectations, to specifying method call arguments, return values, etc.
  • No Record/Replay idioms to learn. Just construct your mock, set it up, use it and optionally verify calls to it (you may not verify mocks when they act as stubs only, or when you are doing more classic state-based testing by checking returned values from the object under test)
  • VERY low learning curve as a consequence of the previous three points. For the most part, you don't even need to ever read the documentation.
  • Granular control over mock behavior with a simple MockBehavior enumeration (no need to learn what's the theoretical difference between a mock, a stub, a fake, a dynamic mock, etc.)
  • Mock both interfaces and classes
  • Override expectations: can set default expectations in a fixture setup, and override as needed on tests
  • Pass constructor arguments for mocked classes
  • Intercept and raise events on mocks
  • Intuitive support for out/ref arguments

We appreciate deeply any feedback that you may have! Feel free to participate in the chat, or report an issue in the issue tracker.

Sponsors

Clarius Org Kirill Osenkov MFB Technologies, Inc. Stephen Shaw Torutek DRIVE.NET, Inc. Ashley Medway Keith Pickford Thomas Bolon Kori Francis Toni Wenzel Giorgi Dalakishvili Uno Platform Dan Siegel Reuben Swartz Jacob Foshee Eric Johnson Ix Technologies B.V. David JENNI Jonathan Oleg Kyrylchuk Charley Wu Jakob Tikjøb Andersen Seann Alexander Tino Hager Mark Seemann Ken Bonny Simon Cropp agileworks-eu sorahex Zheyu Shen Vezel ChilliCream 4OTC

Sponsor this project  

Learn more about GitHub Sponsors

moq4's People

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  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  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  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  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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

moq4's Issues

Problems with Task in 4.2 version

since I updated to the latest version of Moq (4.2) I'm having some unit test failing. I'm getting the System.InvalidCastException: Unable to cast object of type 'FilterCriteria' to type 'SortCriteria'. As my code uses Task's to get these values I suspect the new version of Moq works differently than previous one.

This is the code in question:

In tested class:

Task<FilterCriteria> getFilterCriteriaTask = Task<FilterCriteria>.Factory.StartNew(() => searchService.GetFilterCriteriaFromCache(id));
Task<SortCriteria> getSortCriteriaTask = Task<SortCriteria>.Factory.StartNew(() => searchService.GetSortCriteriaFromCache(id));

FilterCriteria filterCriteria = getFilterCriteriaTask.Result;
SortCriteria sortCriteria = getSortCriteriaTask.Result;

In unit test:

searchServiceMock
   .Setup(it => it.GetFilterCriteriaFromCache(expectedCacheKey, null))
   .Returns(expectedFilterCriteria);

searchServiceMock
   .Setup(it => it.GetSortCriteriaFromCache(expectedCacheKey))
   .Returns(expectedSortCriteria);

Any idea on what it can be due to? I really do not know where to start.

Thanks

Can't Mock class inherited from DBContext

Given the following nuget packages:

<package id="EntityFramework" version="6.0.2-beta1" targetFramework="net45" />
<package id="Moq" version="4.1.1311.0615" targetFramework="net45" />

and code:

public class ClassA : DbContext
{
}

[TestMethod]
public void ShouldntThrowException()
{
     var mock = new Mock<ClassA>();
     var instance = mock.Object;
}

I'm getting an ArgumentException with "Type to mock must be an interface or an abstract or non-sealed class.". However I don't believe this is correct as neither ClassA or DbContext fit this criteria.

Am I missing something?

Support || and ?: in Mock.Of

I think the x || a and x ? a : b should be supported in Mock.Of as long as x can be calculated immediately when mock is set up.

Example:

Mock.Of<INode>(
    m => m.GetProperty("p1").Value == p1
      && (p2 == null || m.GetProperty("p2").Value == p2)
      && (p3 == null || m.GetProperty("p3").Value == p3)
)

Here p1, p2 and p3 are external variables/parameters.
What should happen is if p2 == null, m.GetProperty("p2") is not mocked at all.

4.1 does not support multi-threading

It seems the "fix" for some race conditions in 4.0 was to put locks around mocks internally. This breaks any tests that were using mocks in a multi-threaded way (we've had to roll back to 4.0 for our concurrency tests to work).

If the default is going to be that a mock is not thread-safe, there should at least be some way of opting in to a thread-safe mock. Despite the other issues raised in 4.0, our tests were 100% reliable; but in 4.1 they're 100% broken; so this seems to be a big breaking change in terms of functionality 👎

Provide a quickstart that actually compiles

An IFoo is used but I have to implement everything myself. Resharper does a good job, but still, for example I dont understand how to fulfill the lazy evaluated return param.

Why not give the IFoo in the example?

Allow naming of mocks

Maybe this is a feature already, but I can't see it anywhere.

Fairly often I end up trying to debug error messages like:

Expected: equivalent to < <Castle.Proxies.IWeekTimePeriodProxy>, <Castle.Proxies.IWeekTimePeriodProxy>, <Castle.Proxies.IWeekTimePeriodProxy> >
  But was:  < <Castle.Proxies.IWeekTimePeriodProxy>, <Castle.Proxies.IWeekTimePeriodProxy> >

This would be much easier to do if you could give your mocks a name, which could then be used in a ToString override, so you can easily track which one has ended up where (new Mock<X>("name") or new Mock<X>().WithName("name") would be fine).

I'd be happy to take a look at this, if it was likely to be accepted. Does it sound like something you'd be happy to add?

Allow hidden methods to be mocked

The primary example of this is mocking IEnumerable:

interface IMyCollection : IEnumerable<Item>
{
}

The IEnumerable<Item>.GetEnumerator() actually hides IEnumerator.GetEnumerator(). As a result, this setup code only sets up the generic version

var mock = new Mock<IMyCollection>();
mock.Setup(x => x.GetEnumerator()).Returns(list.GetEnumerator())

When you use Linq methods, like mock.Object.FirstOrDefault(), it tries to use the IEnumerable.GetEnumerator() method. We need a way to conveniently do this setup.

I propose that we also setup all hidden methods/properties by default. So if you do that mock.Setup(x => x.GetEnumerator()), it just works.

I also propose that we support a cast in the Setup expression, mock.Setup(x => ((IEnumerable)x).GetEnumerator()) to be specific about which method we're talking about.

Swapped method arguments will overwrite previous method setup

What steps will reproduce the problem?
When method with two arguments of same type is setup another setup call with swapped arguments will lead to situation where previous setup is removed.

What is the expected output? What do you see instead?
In case when arguments are swapped Mock should still hold reference to two different versions of method invocation setup. First which will get instance A as first argument and B as second argument. Second which have B as first argument and A as second argument.

Please reffer to attached simple code example which will simulate issue very easily.

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

Please provide any additional information below.
Please see attached code example which will lead to incorrect behaviour.
moqincorrectbehaviourexample

unable to mock in unittesting on windows app?

Install-Package : Could not install package 'Moq 4.2.1312.1622'. You are trying to install this package into a project that targets '.NETCore,Version=v4.5.1', but the package does not contain any assembly references or content file
s that are compatible with that framework. For more information, contact the package author.
At line:1 char:1

  • Install-Package Moq
  • - CategoryInfo          : NotSpecified: (:) [Install-Package], InvalidOperationException
    - FullyQualifiedErrorId : NuGetCmdletUnhandledException,NuGet.PowerShell.Commands.InstallPackageCommand
    
    

I would like using moq in a Windows Store App. But this is the message I get from the NUGet PM.

What is going wrong?

Deadlock in Interceptor

When calling Method1 on the mock, and Method one is executing Method2 asynchronously and then waiting for Method2 to complete Moq will cause a deadlock due to the interceptor implementation.

public void Intercept(ICallContext invocation)
{

    lock (Mock) // this solves issue #249
    {
        var interceptionContext = new InterceptStrategyContext(Mock
                                                            , targetType
                                                            , invocationLists
                                                            , actualInvocations
                                                            , behavior
                                                            , orderedCalls
                                                            );
        foreach (var strategy in InterceptionStrategies())
        {
            if (InterceptionAction.Stop == strategy.HandleIntercept(invocation, interceptionContext))
            {
                break;
            }
        }
    }
}

The actual method of the Mock will be called unter lock condition. This will cause a deadlock in some cases. Simple TestCase to reproduce the behavior:

public class ClassToMock
{
    AutoResetEvent reset = new AutoResetEvent(false);
    public virtual void M1()
    {
        var task = new TaskFactory().StartNew(M2);
        Thread.Sleep(500);
        reset.Set();
        task.Wait();
    }

    public virtual void M2()
    {
        reset.WaitOne();
    }
}

[TestMethod]
public void TestMock()
{
    var testMock = new Mock<ClassToMock>{CallBase = true};
    testMock.Object.M1(); // <-- This will never return!
    testMock.Verify(x => x.M1());
    testMock.Verify(x => x.M2());
}

NullReferenceException thrown by Microsoft.CSharp when using Generic Interfaces and Dynamic

I posted this to code.google.com (#376) before realising that the site had moved. The following code produces a NullRef exception

I'm using Win7, Moq 4.2.1402.2112, .NET 4.5.1

The exception occurs when using a mock of the generic interface, when the type argument is of type object. It doesn't occur when:

  1. using a custom reference type or a value type as the type argument,
  2. using a mock of the non-generic interface,
  3. not using moq

The full stack trace of the error is below the code.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Moq;

namespace TestDynamic
{
    public interface IInterface<T>
    {
        T DoStuff(T input);
    }

    public interface IInterface
    {
        object DoStuff(object input);
    }

    class Program
    {
        static void Main(string[] args)
        {
            var m = new MockRepository(MockBehavior.Default);
            var mi = m.Create<IInterface>();
            var miGeneric = m.Create<IInterface<object>>();
            var miGenericString = m.Create<IInterface<string>>();

            var input = new object();
            var expectedOutput = new object();

            mi.Setup(i => i.DoStuff(input)).Returns(expectedOutput);
            miGeneric.Setup(i => i.DoStuff(input)).Returns(expectedOutput);
            miGenericString.Setup(i => i.DoStuff("input")).Returns("output");

            var p = new Program();

            //var output = p.NonGenericDoStuff(mi.Object, input); // ok
            var output = p.GenericDoStuff(miGeneric.Object, input);// throws
            //var output = p.GenericDoStuff(miGenericString.Object, "input"); // ok

            Console.WriteLine(output);
        }

        private T GenericDoStuff<T>(IInterface<T> obj, T input)
        {
            dynamic o = obj;
            var output = o.DoStuff(input);
            return output; // throws NullRef
        }


        private object NonGenericDoStuff(IInterface obj, object input)
        {
            dynamic o = obj;
            var output = o.DoStuff(input);
            return output;
        }
    }
}

Stack trace:

Unhandled Exception: System.NullReferenceException: Object reference not set to an instance of an object.
   at Microsoft.CSharp.RuntimeBinder.ExpressionTreeCallRewriter.GenerateLambda(EXPRCALL pExpr)
   at Microsoft.CSharp.RuntimeBinder.ExpressionTreeCallRewriter.VisitCALL(EXPRCALL pExpr)
   at Microsoft.CSharp.RuntimeBinder.Semantics.ExprVisitorBase.Dispatch(EXPR pExpr)
   at Microsoft.CSharp.RuntimeBinder.Semantics.ExprVisitorBase.Visit(EXPR pExpr)
   at Microsoft.CSharp.RuntimeBinder.ExpressionTreeCallRewriter.Rewrite(TypeManager typeManager, EXPR pExpr, IEnumerable`1 listOfParameters)

   at Microsoft.CSharp.RuntimeBinder.RuntimeBinder.CreateExpressionTreeFromResult(IEnumerable`1 parameters, ArgumentObject[] arguments, Scop
e pScope, EXPR pResult)
   at Microsoft.CSharp.RuntimeBinder.RuntimeBinder.BindCore(DynamicMetaObjectBinder payload, IEnumerable`1 parameters, DynamicMetaObject[] a
rgs, DynamicMetaObject& deferredBinding)
   at Microsoft.CSharp.RuntimeBinder.RuntimeBinder.Bind(DynamicMetaObjectBinder payload, IEnumerable`1 parameters, DynamicMetaObject[] args,
 DynamicMetaObject& deferredBinding)
   at Microsoft.CSharp.RuntimeBinder.BinderHelper.Bind(DynamicMetaObjectBinder action, RuntimeBinder binder, IEnumerable`1 args, IEnumerable
`1 arginfos, DynamicMetaObject onBindingError)
   at Microsoft.CSharp.RuntimeBinder.CSharpConvertBinder.FallbackConvert(DynamicMetaObject target, DynamicMetaObject errorSuggestion)
   at System.Dynamic.DynamicMetaObject.BindConvert(ConvertBinder binder)
   at System.Dynamic.ConvertBinder.Bind(DynamicMetaObject target, DynamicMetaObject[] args)
   at System.Dynamic.DynamicMetaObjectBinder.Bind(Object[] args, ReadOnlyCollection`1 parameters, LabelTarget returnLabel)
   at System.Runtime.CompilerServices.CallSiteBinder.BindCore[T](CallSite`1 site, Object[] args)
   at System.Dynamic.UpdateDelegates.UpdateAndExecute1[T0,TRet](CallSite site, T0 arg0)
   at TestDynamic.Program.GenericDoStuffDynamic[T](IInterface`1 obj, T input) in c:\TFS\TestProjects\TestDynamic\TestDynamic\Program.cs:line
 37
   at TestDynamic.Program.Main(String[] args) in c:\TFS\TestProjects\TestDynamic\TestDynamic\Program.cs:line 27

feature: differentiate crashes from verification errors

When a verification error occurs, the library throws MockException with a proper message. It is OK, but for some corner cases, it would be nicer, if the user code that catches that exception were able to discover whether it is a real error (like mocking nonvirtual method), or just verification failure.

I suppose the best way would be to expose a subclass - VerificationError : MockException to report them, but for the sake of simplicity, I've currently added a trivial MockException.IsVerificationError boolean property

Mocking Interfaces

My apologies if I missed an update or have done something wrong in my code. I have updated my moq version and it seems as though I can no longer mock an interface without receiving a System.TypeLoadException? Any help with this issue? The following is a simple snippet of code that is generating the error:

using Moq;
namespace ConsoleApplication4 {
    class Program {
        static void Main(string[] args) {

            //Mock<ICrapGoat> asdf = new Mock<ICrapGoat>(); // <-- Throws System.TypeLoadException
            Mock<CrapGoat> asdf = new Mock<CrapGoat>(); // <-- Need to use concrete instance
            var asdfsdfvcsdafr = asdf.Object;
        }
    }

    public interface ICrapGoat {}
    public class CrapGoat : ICrapGoat {}
}

Issue with System.Reflection.Missing object passed as an argument to mocked Method

I am using moq with Office Interop. For some reason default value for optional argument in property Worksheet.Range, is set to System.Reflection.Missing this leads to an exception when Mocked delegate is invoked via DynamicInvoke method in

public static object InvokePreserveStack(this Delegate del, params object[] args)

with one of the arguments set to System.Reflection.Missing.

Following code reproduces problem (might have some bug as it is converted from VB. Net).

public void ReflectionTest()
{
    Mock<Excel._Worksheet> xrm = new Mock<Excel._Worksheet>();

xrm.Setup(f => f.Range(It.IsAny<string>)).Returns(new Func<object, object, Excel.Range>(RangeReturnFunction))

    object k = xrm.Object.Range("A1");

}

public Excel.Range RangeReturnFunction(object s, object xv = null)
{
    Mock<Excel.Range> z = new Mock<Excel.Range>();
    return z.Object;
}

Cannot use Mock<T>.Raise() on WPF Routed Events

Hi,

Trying to unit test some WPF-related code and in that situation, I'm trying to get the code below to work:

var listView = new Mock<ListView>();
listView.Raise(lv => lv.Unloaded += null, EventArgs.Empty);

However, this gives me an ArgumentNullException with the following message:

Value cannot be null.Parameter name: handler 

Skipping the EventArgs.Empty makes no difference.

If I change my example to something like this:

void Main()
{
    var listView = new Mock<ListView>();
    listView.Raise(lv => lv.Unloaded += Foo);   
}

void Foo(object sender, RoutedEventArgs e)
{
}

...I get a different exception (ArgumentException).

Expression is not an event attach or detach, or the event is declared in a
class but not marked virtual

So, is the conclusion basically that we cannot mock these events, since they aren't virtual? That's what the exception message is telling me, but I just want to check... Are there any other realistic test scenarios for 3rd party classes which uses events?

Add support for code contracts

At the moment, Moq offers no support for Code Contracts, which is included in C# 4.0.

While we can disable code contracts on test assemblies, contracts often provide very useful information about the external facing requirements of our libraries, so this is a less-than-ideal solution.

The workaround to this is to include intermediary assumptions about the library. This is highly verbose, and completely clutters up any tests using code contracts.

Entity mock = Mock.Of<Entity>();
Contract.Assume(mock != null);
entityUser.use(mock);

For anything that requires a non-null object by contract, we would need to explicitly specify an assumption about the output of the Moq library. This requires a huge amount of extra intermediary code, at least one assumption for every mock.

The best alternative is to include code contract information in the Moq library itself, which would provide clear guarantees as to the preconditions and postconditions of the Moq API.

It's worth noting that this is likely worth doing in and of itself as code contracts can add a great degree of robustness to an existing library.

Counting number of call method before callback raise

Why counting number of call mock method is realized after callback raise?
I perform following code for working imitation:

mock.Verify(m=>m.Execute()).Callback(()=>{Thread.Sleep(1000)}); // work imitations

But number of Execute method calls is changed after imitation have been completed.
Thanks.

ps: sorry, my English is very bad

NullReferenceException when mocked method has a nullable value type argument, but It.IsAny constraint is not nullable

Example:

public interface ISomeInterface {
    void DoSomething(Guid? guid);
}

mock.Setup(x => x.DoSomething(It.IsAny<Guid>()))
mock.Object.DoSomething(null);

Result:

System.NullReferenceException : Object reference not set to an instance of an object.
    at Moq.Match`1.Matches(Object value)
    at Moq.MethodCall.Matches(ICallContext call)
    at System.Linq.Enumerable.LastOrDefault(IEnumerable`1 source, Func`2 predicate)
    at Moq.ExtractProxyCall.HandleIntercept(ICallContext invocation, InterceptStrategyContext ctx)
    at Moq.Interceptor.Intercept(ICallContext invocation)
    at Castle.DynamicProxy.AbstractInvocation.Proceed()
    at Castle.Proxies.ISomeInterfaceProxy.DoSomething(Nullable`1 guid)

Moq still doesn't support multithreading

Just came across following issue with Moq (4.2.1312.1622). Consider interface:

public IMyInterface
{
    void Do(int arg);
}

... setup:

var mock = Mock.Create<IMyInterface>();
mock.Setup(x => x.Do(0)).Verifiable();
mock.Setup(x => x.Do(1)).Verifiable();

... and invocation:

var obj = mock.Object;
var t1 = Task.Run(() => obj.Do(0));
var t2 = Task.Run(() => obj.Do(1));

Task.WhenAll(t1, t2).Wait();
mock.Verify();

Every now and then this verification will fail saying that one of two setups was not matched. But will succeed if changed to:

mock.Verify(x => x.Do(0), Times.Once);
mock.Verify(x => x.Do(1), Times.Once);

This happens because method call invocation logic inside Interceptor is not thread safe. When Interceptor.Intercept method is called it creates strategy pipeline, one of strategies in this pipeline - ExtractProxyCall - locates matched method call and places it into InterceptStrategyContext.CurrentCall. Which is later used by ExecuteCall strategy to do the actual call.

The problem here is that both executing threads will work with same InterceptorContext instance. So when executed in parallel it's possible of one ExtractProxyCall strategy to overwrite method call just located by another ExtractProxyCall strategy, that way both ExecuteCall strategies will end up executing same method call twice. This can easily be confirmed by attaching callbacks to original setups.

mock.Verify(x => ...) on the other hand does verification evaluating given expression against collected call contexts which, obviously, contains correct information.

Provide better error reporting in Verify()

Example of reporting I get in 4.1.1311.615:

Moq.MockException : 
Expected invocation on the mock at least once, but was never performed:
r => r.Save(It.Is<Entity>(e => e.Description == .expectedDescription))
No setups configured.

Performed invocations:
IRepository`2.Save(My.Entity)

Reporting that would be more useful:

Moq.MockException : 
Expected invocation on the mock at least once, but was never performed:
r => r.Save(It.Is<Entity>(e => e.Description == "ABC"))
No setups configured.

Performed invocations:
IRepository`2.Save(My.Entity { Description = "XYZ" })

As for the second point, I have done similar thing once -- can be done by finding all distinct property/method paths in expression tree passed to It.Is and requesting their values for actual argument.

Can't setup protected methods with nullable parameters

It seems that it's not possible to set up a protected method if it has nullable parameters.

Example:

public abstract class MyService
{
    protected abstract void MyMethod(int? val);
}

class Program
{
    static void Main(string[] args)
    {
        var mock = new Mock<MyService>();

        mock.Protected().Setup("MyMethod", (int?)1);
    }
}

The output of running this program is an ArgumentException with the following message:

Expression of type 'System.Int32' cannot be used for parameter of type 'System.Nullable1[System.Int32]' of method 'Void MyMethod(System.Nullable1[System.Int32])'

Bug using Mock.Of on objects with virtual properties.

The pull request #9 attempts to fix this, but there are still a few cases it doesn't work. Append the following code at the end of
QueryableMocksFixture and you'll see the tests fail.

    public class Foo
    {
        protected Foo()
        {
        }

        public virtual string Value { get; private set;}
    }

    public class FooFixture
    {
        [Fact]
        public void Test()
        {
            var remote = Mock.Of<Foo>(rt => rt.Value == "foo");
            Assert.Equal("foo", remote.Value);
        }
    }

    public interface IBar
    {
        Foo Foo { get; set; }
    }

    public class BarFixture
    {
        [Fact]
        public void Test()
        {
            var remote = Mock.Of<IBar>(rt => rt.Foo.Value == "foo");
            Assert.Equal("foo", remote.Foo.Value);
        }
    }

Verifiable throw NullReferenceException for async Task methods

Have interface

 public interface IDataStoreService
    {
        Task<T> GetDataAsync<T>(string key);
        Task SaveDataAsync<T>(string key, T item, bool storeAlways = false);
    }

In test create mock object

 var mockDataService = new Mock<IDataStoreService>();
            mockDataService.Setup(
                service => service.SaveDataAsync(It.IsAny<string>(), It.IsAny<object>(), It.IsAny<bool>())).Verifiable();

Act it with this code

 var settingsService = new MyStorageService(mockDataService.Object);
  var rez = await settingsService.Set("setting", "ok");

Moq throws NullReferenceException on SaveDataAsync call in MyStorageService.

If I change interface method to

   Task<bool> SaveDataAsync<T>(string key, T item, bool storeAlways = false);

and change setup to

   mockDataService.Setup(
                service => service.SaveDataAsync(It.IsAny<string>(), It.IsAny<object>(), It.IsAny<bool>())).ReturnsAsync(true);

all works fine.

Support for Xamarin.iOS and Xamarin.Android

I've tried using Moq for unit testing on these platforms and seem unable to do so. Has anyone checked whether this is feasible or not? I think trying to move this to a PCL would help with this matter. I can look into it myself if that is fine? I'm new to helping out with an open source project. I love using moq for testing and would like to use it on those platforms.

Override previous setup

Hi I am trying to set an mock of a class's method with two possible input. When i check output only the last set up return expected output. The first one did not. Any help is much appreciated.

[Test]
public void ClimbOnceTwoNeighbour_Sample()
{
 stateConverter = new Mock<StateConverter>();

solution = new Mock<Solution>();
state = new Mock<State>();

var neightbourSolution1 = new Mock<Solution>();
var neighbourState1 = new Mock<State>();
var neightbourSolution2 = new Mock<Solution>();
var neighbourState2 = new Mock<State>();

stateConverter.Setup(x => x.FromSolution(neightbourSolution1.Object, It.IsAny<State>())).Returns(neighbourState1.Object);
stateConverter.Setup(x => x.FromSolution(neightbourSolution2.Object, It.IsAny<State>())).Returns(neighbourState2.Object);

var state1 = stateConverter.Object.FromSolution(neightbourSolution1.Object, state.Object);//return null ????
var state2 = stateConverter.Object.FromSolution(neightbourSolution2.Object, state.Object);//return neighbourState2.Object)


Assert.AreEqual(neighbourState2.Object, state2);//pass test here
Assert.AreEqual(neighbourState1.Object, state1);//fail here due to null is returned from previous statement

}

System.InvalidCastException when invoking method that starts with "add"

Hello, I faced with the problem when i used Moq.
I wrote the simple test

public interface ILogger
{
    void add_info(string info);
    void Add_info(string info);
}

[TestFixture]
public class Class1
{
    [Test]
    public void Test_add_info()
    {
        var mock = new Mock<ILogger>();
        mock.Setup(x => x.add_info(It.IsAny<string>()));
        mock.Setup(x => x.Add_info(It.IsAny<string>()));

        mock.Object.add_info("asd");
        //mock.Object.Add_info("asd");
    }
}

When i call

mock.Object.add_info("asd");

it throws
System.InvalidCastException : Не удалось привести тип объекта "System.String" к типу "System.Delegate".
в Moq.AddActualInvocation.HandleIntercept(ICallContext invocation, InterceptStrategyContext ctx)
в Moq.Interceptor.Intercept(ICallContext invocation)
в Castle.DynamicProxy.AbstractInvocation.Proceed()
в Test.Class1.Test_add_info() в Class1.cs: line 22

Sorry, i have Russian VS, it says: "Can't cast System.String to System.Delegate". But, when i call

mock.Object.Object.Add_info("asd");

string, it works.
I use VS 2012, .NET4.5. Nuget packages - NUnit, Moq(v.4.2.1312.1622). The Code was runned from Resharper test runner.

Fix issue #325

We're mocking a class C that doesn't implement interface I. The interface is added to the mock via As<I>(). However class C has many methods and we need them to work in tests as usually so we use CallBase = true. But the interface I doesn't have any "base".

The interface I has an event E. We want to be able to add handlers for the event and raise it via Raise(Action<T>, EventArgs) method. However adding a handler throws exception since there is no base implementation for the event.

Doesn't support .NET Core 4.5.1 (can't install)

Can't install Moq from NuGet to my project. This is what it says:

Installing 'Moq 4.2.1312.1622'.
Successfully installed 'Moq 4.2.1312.1622'.
Adding 'Moq 4.2.1312.1622' to MyProj.Library.Tests.
Uninstalling 'Moq 4.2.1312.1622'.
Successfully uninstalled 'Moq 4.2.1312.1622'.
Install failed. Rolling back...
Could not install package 'Moq 4.2.1312.1622'. You are trying to install this package
into a project that targets '.NETCore,Version=v4.5.1', but the package does not 
contain any assembly references or content files that are compatible with that
framework. For more information, contact the package author.

Allow setting up async methods easily

It would be nice to have better usability for methods that return Task.

For example, an option for doing something like:

myMock.Setup(x => x.ReadAsync()).ThrowsAsync(new Exception());

which should return a faulted task with that exception.

Also, for methods that return Task that are not explicitly set up, it would be good that instead of defaulting to return a null Task, that they return a completed Task (or completed Task) instead.

Didn't consider the best way to address this yet, but currently it can be a little cumbersome especially when mocking code where >70% of its methods are async.

Recursive property setup overrides previous setups

Apologies for the cryptic subject. It's difficult to explain this without an example.

Here's a failing test:

var baz = Mock.Of<Baz>(x => x.Value == "beforeBaz");
var qux = Mock.Of<Qux>(x => x.Value == "beforeQux");

var bar = Mock.Of<Bar>(x =>
    x.Baz == baz &&
    x.Qux == qux);

var obj = Mock.Of<Foo>(x => x.Bar == bar);

var mock = Mock.Get(obj);

obj.Bar.Baz.Value.ShouldBe("beforeBaz"); // Pass
obj.Bar.Qux.Value.ShouldBe("beforeQux"); // Pass

mock.SetupGet(x => x.Bar.Baz.Value).Returns("test");

obj.Bar.Baz.Value.ShouldBe("test"); // Pass
obj.Bar.Qux.Value.ShouldBe("beforeQux"); // Fail

Effectively I've set up the return value of Foo.Bar, Bar.Qux and Qux.Value separately and then used the call the SetupGet to override the value of Foo.Bar.Baz.Value. This replaces the previously setup Foo.Bar with a new mock without the registration of Bar.Qux.

Not sure whether this is an edge case you want to support but I'm not sure of the best way to work around it. Any help would be greatly appreciated

Mock class's method with multiple parameter only take last paramter

Hi I have tried to mock and class and set up it as followed. What ever I tried only one assert return is true. I have tired to replace Input with String and Output class with int and its works fine. Any suggestion please? Thank you very much

[TestFixture]
class TestSample
{
[Test]
public void Test1()
{
    Mock<SampleClass> mockObject = new Mock<SampleClass>();
    var  mockInput1 = new Mock<InputClass>();
    var mockInput2 = new Mock<InputClass>();
    var mockOutPut1 = new Mock<OutputClass>();
    var mockOutPut2 = new Mock<OutputClass>();
    mockObject.Setup(x => x.Get(mockInput1.Object)).Returns(mockOutPut1.Object);
    mockObject.Setup(x => x.Get(mockInput2.Object)).Returns(mockOutPut2.Object);

    var returned = mockObject.Object.Get(mockInput1.Object);
    Assert.AreEqual(mockOutPut1, returned);

    returned = mockObject.Object.Get(mockInput2.Object);
    Assert.AreEqual(mockOutPut2, returned);

    returned = mockObject.Object.Get(mockInput1.Object);
    Assert.AreEqual(mockOutPut1, returned);
}
}

public class SampleClass
{
public  virtual OutputClass Get(InputClass a)
{
    return null;
}
}

public class InputClass {}
public class OutputClass {}

Implement verification of event handler attaches and detaches (something like `mock.Verify(m => m.Event += callback)`)

I'm working on some code where an object subscribes a private method to an event of a passed-in class. In my unit tests I'd like to see how many handlers have been attached to the event. There should only be one, but it is possible that there could be more than one (I know this because I had a bug that let the += execute twice). I wanted to write a unit test to report when this happens.

I saw this question on the old MOQ site, but there haven't been any updates in a while. Is it still an open request? https://code.google.com/p/moq/issues/detail?id=100

Thanks

MockDefaultValueProvider does not support Task<T> results

When using the MockDefaultValueProvider, methods with a return type of Task will get an empty Task (provided by the EmptyDefaultValueProvider) as the default value.

Expected behavior is to return a mock wrapped in a completed Task.

Related to #73

How can I mock a function with ref parameter?

I have this simple code, but I can't do it work

[TestMethod]
        public void TestMoq()
        {
            var mock = new Moq.Mock<Hola>();            

            string o = "1";
            mock.Setup(x => x.DoSomething(ref o)).Callback((string a) => o = "2");

            mock.Object.DoSomething(ref o);

        }
public class Hola
    {
        public Hola()
        {

        }

        public virtual void DoSomething(ref string a)
        {

        }
    }

The error is this:
capturemoqbug

I prefer to use the Moq library. But only I get it on the Rhino Mocks library, with the function OutRef:

[TestMethod]
        public void TestRhinoMocks()
        {
            MockRepository mocker = new MockRepository();

            Hola mock = mocker.StrictMock<Hola>();

            string o = "1";

            Expect.Call(() => mock.DoSomething(ref o)).OutRef("2");

            mocker.ReplayAll();

            //i.Setup(x => x.DoSomething(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>())).Callback((string a, string b, string c) => o = "2");

            mock.DoSomething(ref o);
        }

Thanks in advance!

ref keyword in interface method declaration causes exception

I'm writing unittests for an application which makes use of a third party API, with some generated interfaces. I was getting some strange exceptions trying to create a mock object for a complex interface. After much digging, I found that one of these interfaces it extends has a declaration with a ref keyword in it:

public interface IReferenceMaker
{
   RefResult NotifyRefChanged(ref UIntPtr partID, RefMessage message);
}

When trying to create a mock object for this interface, an exception is thrown when accessing the Object property: ArgumentException: Type System.UIntPtr could not be converted to a OpCode.

Mock<IReferenceMaker> mockRefMaker = new Mock<IReferenceMaker>();
IReferenceMaker refMaker = mockRefMaker.Object;

Unfortunately I can't change the interface in any way, so I'm looking for a way to work around the issue on the Moq side.
Any ideas?

edit: I noticed in the stacktrace that the exception is thrown in Castle, so I submitted an issue report there too.

Documentation

Love your product. Please clean up and elaborate on your product functionality within the documentation
.
Thanks

Ordered call issue with invocations with same arguments in MockSequence

When multiple invocations with the same arguments are defined consecutive on a mock, then the last matching method call is used instead of the method call corresponding with the current sequence step.

This is because while scanning for a matching method call, the sequence step is incremented on each match. This causes subsequent method calls with matching arguments - even though their sequence step is higher then the current step - to be considered as candidate.

I've added the following test which currently fails on the first assert (Expected: 101, Actual: 102):

    [Fact]
    public void SameMockRightSequenceMultipleInvocationsWithSameArguments()
    {
        var a = new Mock<IFoo>(MockBehavior.Strict);

        var sequence = new MockSequence();
        a.InSequence(sequence).Setup(x => x.Do(100)).Returns(101);
        a.InSequence(sequence).Setup(x => x.Do(100)).Returns(102);
        a.InSequence(sequence).Setup(x => x.Do(200)).Returns(201);
        a.InSequence(sequence).Setup(x => x.Do(100)).Returns(103);

        Assert.Equal(101, a.Object.Do(100));
        Assert.Equal(102, a.Object.Do(100));
        Assert.Equal(201, a.Object.Do(200));
        Assert.Equal(103, a.Object.Do(100));
    }

I'll provide a PR which adds this test, and the corresponding fix.

Upgrade to Castle.Core 3.2.1 because of Mono

There is a fix in Castle.Core castleproject/Core@9f0577f that fixes http://stackoverflow.com/questions/18034341/system-collections-generic-keynotfoundexception-with-mono-but-not-microsofts

git tag --contains 9f0577fc in Castle.Core show that this fix was released first in 3.2.1 but Moq is using 3.2.0. A diff shows that there wasn't to much code change so I'm hoping that an upgrade will not be to painful.

Main reason for asking for this is that we are trying to get ScriptCs test to run on mono and because we are using Moq, this is a huge blocker.

Mocks.Of in the quickstart

I didn't realise Mocks.Of existed until digging around the internet / the api.

It would be great to feature it in the QuickStart.

Windows Phone 8 version

Any plans for a Windows Phone 8 version, ideally a Nuget package? The Silverlight dll works with Windows Phone 8, but a Nuget package would be nice.

Allow chaining of Setup().Returns()

I'd love to be able to do this:

mock
  .Setup(x => x.Method1())
  .Returns(value1)
  .Setup(x => x.Method2())
  .Returns(value2);

Any reason we wouldn't want to add this feature? If it's cool, I'll create the PR.

Mock.As appears to be broken in Moq 4.1.1308.2321

The following works as expected in 4.0.10827 but in 4.1.1308.2321 the foo as IDisposable cast doesn't succeed.

public interface IFoo
{
    void Bar();
}

[TestFixture]
public class Tests
{
    [Test]
    public void Test()
    {
        var mock = new Mock<IFoo>();
        mock.Setup(x => x.Bar());
        mock.As<IDisposable>().Setup(x => x.Dispose());

        Action<IFoo> testMock = (IFoo foo) =>
        {
            foo.Bar();

            var disposable = foo as IDisposable;

            if (disposable != null)
            {
                disposable.Dispose();
            }
        };

        testMock(mock.Object);

        mock.VerifyAll();
    }

MockSequence and VerifyAll

When using a "MockSequence" the behavior of the "VerifyAll" method is modified. Is this correct?

public interface IFoo
{
    void Do();
}

/*
 * Throws MockVerificationException
 */
var foo = new Mock<IFoo>(MockBehavior.Strict);

foo.Setup(f => f.Do());
foo.VerifyAll();

/*
 * Does not throw MockVerificationException
 */
var foo = new Mock<IFoo>(MockBehavior.Strict);
var seq = new MockSequence();

foo.InSequence(seq).Setup(f => f.Do());
foo.VerifyAll();

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.