moq / moq4 Goto Github PK
View Code? Open in Web Editor NEWThe most popular and friendly mocking framework for .NET
License: Other
The most popular and friendly mocking framework for .NET
License: Other
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 {}
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.
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;
}
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.
Reported by project member bcardiff, Mar 23, 2008
Implement MockSequence idea (as explained at
http://groups.google.com/group/moqdisc/browse_thread/thread/80404b259824812d
by Eugene) on top of Moq public interface.
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
- 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?
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());
}
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
This allows the setup to invoke the base class behavior.
I didn't realise Mocks.Of existed until digging around the internet / the api.
It would be great to feature it in the QuickStart.
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)
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
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);
}
}
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.
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
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?
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.
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:
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
Love your product. Please clean up and elaborate on your product functionality within the documentation
.
Thanks
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();
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)
{
}
}
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!
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?
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 👎
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 {}
}
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.
See the issue reported here: https://code.google.com/p/moq/issues/detail?id=349
BTW. Why there's no mention on the Google Project site that Moq has new source code repo?
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.
This is not so much an issue with the framework itself; more so with "appearances".
Navigating to moqthis.com produces a GitHub-branded 404 error.
It is difficult to sell this project to a team when first impressions suggest that the project is dead/no longer active. https://code.google.com/p/moq/ is outdated, and certain links are broken (API documentation, for instance: http://clariusconsulting.net/labs/moq/index.html).
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.
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
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.
Add documentation to NuGet package and/or have updated easy to find online documentation.
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.
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.
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.
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?
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.
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?
http://www.clariusconsulting.net/labs/moq/html/90760C57.htm does not work, can we please get this corrected?
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
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
}
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
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.
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();
}
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.
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.
I think there's some leftover git merge markup in Interceptor.cs:
line157 <<<<<<< HEAD
line 250 =======
line 259 >>>>>>> upstream/dev
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.
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.Nullable
1[System.Int32])'
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.
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.