I am developing tests for an application. There's a method that has a params array as a parameter. I have set up the method using Moq but when I run the test, the return value of the method is null, which means it is not being mocked.
Here's a code sample:
public interface ITicketManager {
string GetFirstTicketInQueueIfMatches(params string[] ticketsToMatch);
}
public class TicketManager : ITicketManager {
private Queue<string> ticketQueue = new Queue<string>();
public string GetFirstTicketInQueueIfMatches(params string[] ticketsToMatch) {
var firstQueuedTicket = ticketQueue.Peek();
var firstQueuedTicketMatchesAnyOfRequested = ticketsToMatch.Any(t => t == firstQueuedTicket);
if(firstQueuedTicketMatchesAnyOfRequested)
return firstQueuedTicket;
return null;
}
}
The mock code looks like this:
var mock = new Mock<ITicketManager>();
mock.Setup(m => m.GetFirstTicketInQueueIfMatches(It.IsAny<string>()))
.Returns(p => {
if(p.Contains("A"))
return "A";
return null;
});
Why is it never hitting the mocked method?
You're trying to call a method taking a single string, rather than an array. Bear in mind that it's the C# compiler which handles the params part, converting calling code which just specifies individual values into a call passing in an array. As far as the method itself is concerned, it's just getting an array - and that's what you're mocking.
The compiler is actually turning your code into:
mock.Setup(m => m.GetFirstTicketInQueueIfMatches
(new string[] { It.IsAny<string>() }))
which isn't what you want.
You should use:
mock.Setup(m => m.GetFirstTicketInQueueIfMatches(It.IsAny<string[]>()))
If you need to verify that it only gets given a single value, you'll need to do that in the same way you would for a non-params parameter.
Basically, params only makes a difference to the C# compiler - not to moq.
I believe the params string has to be matched by It.IsAny<string[]>() rather than It.IsAny<string>()
Using Moq, the code below works to setup a callback on a method with a params argument. Defining the second argument as an array does the trick.
MockLogger
.Setup(x => x.Info(It.IsAny<string>(), It.IsAny<object[]>()))
.Callback<string, object[]>((x, y) => _length = x.Length);
Related
I am not sure how to pass arguments from Setup() to Returns() in Moq.
Here is an example:
public static IInterfaceHandler GetInterfaceHandlerMoq()
{
// Defining the moq
var moq = new Mock<IInterfaceHandler>();
// Trying to set up a moq using another moq
moq.Setup(m => m.CreateCommunicationInterface(It.IsAny<Guid>(), It.IsAny<string>()))
.Returns((Guid guid, string value) => GetProgrammerMoq(guid, value));
// Return mocked object
return moq.Object;
}
Note that GetProgrammerMoq() is a library that will return another Moq. Here is the code:
public static IProgrammer GetProgrammerMoq(Guid guid, string instName)
{
// Create Moq
var moq = new Mock<IProgrammer>();
// Set up the returnables
moq.Setup(o => o.InstanceName).Returns(programmer + "_" + instName);
moq.Setup(o => o.Guid).Returns(guid);
// Return mocked object
return moq.Object;
}
See here that GetProgrammerMoq() needs its arguments to be set up based on what is passed to CreateCommunicationInterface().
My test then tries to get and use the Moq, but "p" is returned as null (because, I guess, my arguments are not passed properly to Returns()).
Here is a draft of what the test is to look like:
[Fact]
public void DoSomething()
{
IInterfaceHandler test = ProgrammerMoqs.GetInterfaceHandlerMoq();
Guid? g = new Guid();
IProgrammer p = test.CreateCommunicationInterface(g, "test-boff");
...
}
Try this:
var moq = new Mock<IInterfaceHandler>(MockBehavior.Strict);
MockBehavior.Strict: if you get NULLs from Mock, then always try MockBehavior.Strict. When some setup is not prepared, Moq by default returns NULL. But with MockBehavior.Strict, it will throw an exception. Every single attempt to call anything from the mock object, if it lacks proper setup, will throw.
If you get an exception when trying MockBehavior.Strict, then it means that the:
.Setup(m => m.CreateCommunicationInterface(It.IsAny<Guid>(), It.IsAny<string>()))
failed to catch the invocatio, so the mock returned NULL by default.
Why did it fail to catch the invocation? There are several options:
CreateCommunicationInterface may be overloaded and your setup matched another overload that you did not expect
filters (It.IsAny..) didn't match the actual arguments
(..)
Klaus Gütter noted in the comments about the difference of Guid and Guid?. In fact, the filter you are using is It.IsAny() while in the test you pass:
Guid? g = new Guid();
g is not an object of type Guid, it's Nullable<Guid>, hence the filter looking for any-Guid did not match. The code compiled, because the result of the expression It.IsAny<Guid>() fits Guid? wanted by the method, but still the types don't match.
If you try It.IsAny<Guid?>() it will probably match fine and return what you wanted.
moq.Setup(m => m.CreateCommunicationInterface(It.IsAny<Guid?>(), It.IsAny<string>()))
.Returns((Guid? guid, string value) => GetProgrammerMoq(guid, value));
I have a unit test using MOQ that's behaving unexpectedly. I'm expecting the IsAuthorizedAsync method to always return true, but it's returning false. Here's a simplified version of the code that's adding the IsAuthorizedAsync method to my Mock Object.
public static IAuthenticationInterface GetAuthentication()
{
var mock = new Mock<IAuthenticationInterface>();
mock.Setup(e => e.IsAuthorizedAsync(It.IsIn<string>(), It.IsAny<MyEvent>())).Returns(System.Threading.Tasks.Task.FromResult(true)).Verifiable();
// return the mock object
return mock.Object;
}
Here's code similar to the code that's using it:
bool isAuthorized = this.mockObject != null && await this.mockObject.IsAuthorizedAsync("abc123", myEvent).ConfigureAwait(false);
Like I said, it's returning false when it looks to me like it should always return true. Is there any way for me to step into the lambda expression code? Alternatively, is there any way for me to view what the actual lambda expression that's being used when I call this.mockObject.IsAuthorizedAsync? I suspect it's not what I think it is.
-Eric
As per #tzachs' comment, note that the It.IsIn matcher takes a list of matching values (strings in your instance). It.IsIn() with an empty params or IEnumerable will never match anything, as it is implemented with .Contains:
public static TValue IsIn<TValue>(IEnumerable<TValue> items)
{
return Match.Create<TValue>((Predicate<TValue>)
(value => Enumerable.Contains<TValue>(items, value)),
(Expression<Func<TValue>>) (() => It.IsIn<TValue>(items)));
}
hence the failure to return the desired result. You'll want to either change this e.g.
It.IsAny<string>() // ... Any string at all
It.Is<string>(s => s == "Foo") // ... Match via a Predicate
It.IsIn<string>("Foo", "Bar", "Baz") // ... Match via a List
Also, note that when working with Async methods, that Moq (and Test Frameworks like NUnit and XUnit) have support for Async semantics. So instead of 'hacking' a Task.FromResult, what you can do instead is:
[Test]
public async void MyTest() // ... The UT can be made async
{
var mock = new Mock<IAuthenticationInterface>();
mock.Setup(e => e.IsAuthorizedAsync(It.IsIn<string>("Foo"), It.IsAny<MyEvent>()))
.ReturnsAsync(true) // ... Async
.Verifiable();
// async calls can be awaited
Assert.True(await mock.Object.IsAuthorizedAsync("Foo", null));
}
(and yes, I know I'm just testing the Mock here :)
I am a bit confused on Moq call. I need to Moq a function that takes an object. It should return a different object, whose content is generated by an existing function, that takes its input from field of the input object.
So I supply a complex object in input, and one of its fields is equal to some number, and I need to reply with object that is generated taking into account that some number.
I came up with the following sketch but it is full of errors. I appreciate a proper primer how to do what I need.
var processor = new Mock<IMyCommandProcessor>();
processor.Setup(d => d.ProcessCommand(It.IsAny<MyCommand>))
.Returns((MyResponse r) => r.Results = new List{ newDto(aaa) });
newDto(aaa) is the call of a function, and instead of aaa I need a field that comes from MyCommand object given from input. How I can declare mocking here? Thanks a lot!
If newDto(aaa) is a call to a helper function then you could try:
processor.Setup(d => d.ProcessCommand(It.IsAny<MyCommand>))
.Returns((MyCommand c) => new MyResponse(){ Results = new List<DtoType>(){ newDto(aaa)}});
Just a generic example :
you can replace input + input with any method of course.
[Test]
public void TestMock()
{
var a = new Mock<IDictionary<string, string>>();
a.Setup(d => d[It.IsAny<string>()]).Returns((string input) => input + input);
string result = a.Object["test"];
}
You should use input parameters in Returns callback:
processor.Setup(d => d.ProcessCommand(It.IsAny<MyCommand>))
.Returns((MyCommand c) => new MyResponse()});
However you cannot access the newDto function if it's defined on the class you are testing.
I want a mock that returns 0 the first time, then returns 1 anytime the method is called thereafter. The problem is that if the method is called 4 times, I have to write:
mock.SetupSequence(x => x.GetNumber())
.Returns(0)
.Returns(1)
.Returns(1)
.Returns(1);
Otherwise, the method returns null.
Is there any way to write that, after the initial call, the method returns 1?
The cleanest way is to create a Queue and pass .Dequeue method to Returns
.Returns(new Queue<int>(new[] { 0, 1, 1, 1 }).Dequeue);
That's not particulary fancy, but I think it would work:
var firstTime = true;
mock.Setup(x => x.GetNumber())
.Returns(()=>
{
if(!firstTime)
return 1;
firstTime = false;
return 0;
});
Bit late to the party, but if you want to still use Moq's API, you could call the Setup function in the action on the final Returns call:
var mock = new Mock<IFoo>();
mock.SetupSequence(m => m.GetNumber())
.Returns(4)
.Returns(() =>
{
// Subsequent Setup or SetupSequence calls "overwrite" their predecessors:
// you'll get 1 from here on out.
mock.Setup(m => m.GetNumber()).Returns(1);
return 1;
});
var o = mock.Object;
Assert.Equal(4, o.GetNumber());
Assert.Equal(1, o.GetNumber());
Assert.Equal(1, o.GetNumber());
// etc...
I wanted to demonstrate using StepSequence, but for the OP's specific case, you could simplify and have everything in a Setup method:
mock.Setup(m => m.GetNumber())
.Returns(() =>
{
mock.Setup(m => m.GetNumber()).Returns(1);
return 4;
});
Tested everything here with xunit#2.4.1 and Moq#4.14.1 - passes ✔
You can use a temporary variable to keep track of how many times the method was called.
Example:
public interface ITest
{ Int32 GetNumber(); }
static class Program
{
static void Main()
{
var a = new Mock<ITest>();
var f = 0;
a.Setup(x => x.GetNumber()).Returns(() => f++ == 0 ? 0 : 1);
Debug.Assert(a.Object.GetNumber() == 0);
for (var i = 0; i<100; i++)
Debug.Assert(a.Object.GetNumber() == 1);
}
}
Just setup an extension method like:
public static T Denqueue<T>(this Queue<T> queue)
{
var item = queue.Dequeue();
queue.Enqueue(item);
return item;
}
And then setup the return like:
var queue = new Queue<int>(new []{0, 1, 1, 1});
mock.Setup(m => m.GetNumber).Returns(queue.Denqueue);
Normally, I wouldn't bother submitting a new answer to such an old question, but in recent years ReturnsAsync has become very common, which makes potential answers more complicated.
As other have stated, you can essentially just create a queue of results and in your Returns call pass the queue.Dequeue delegate.
Eg.
var queue = new Queue<int>(new []{0,1,2,3});
mock.SetupSequence(m => m.Bar()).Returns(queue.Dequeue);
However, if you are setting up for an async method, we should normally call ReturnsAsync. queue.Dequeue when passed into ReturnsAsync and will result in the first call to the method being setup working correctly, but subsequent calls to throw a Null Reference Exception. You could as some of the other examples have done create your own extension method which returns a task, however this approach does not work with SetupSequence, and must use Returns instead of ReturnsAsync. Also, having to create an extension method to handle returning the results kind of defeats the purpose of using Moq in the first place. And in any case, any method which has a return type of Task where you have passed a delegate to Returns or ReturnsAsync will always fail on the second call when setting up via SetupSequence.
There are however two amusing alternatives to this approach that require only minimal additional code. The first option is to recognize that the Mock object's Setup and SetupAsync follow the Fluent Api design patterns. What this means, is that technically, Setup, SetupAsync, Returns and ReturnsAsync actually all return a "Builder" object. What I'm referring to as a Builder type object are fluent api style objects like QueryBuilder, StringBuilder, ModelBuilder and IServiceCollection/IServiceProvider. The practical upshot of this is that we can easily do this:
var queue = new List<int>(){0,1,2,3};
var setup = mock.SetupSequence(m => m.BarAsync());
foreach(var item in queue)
{
setup.ReturnsAsync(item);
}
This approach allows us to use both SetupSequence and ReturnsAsync, which in my opinion follows the more intuitive design pattern.
The second approach is to realize that Returns is capable of accepting a delegate which returns a Task, and that Setup will always return the same thing. This means that if we were to either create an an extension method for Queue like this:
public static class EMs
{
public static async Task<T> DequeueAsync<T>(this Queue<T> queue)
{
return queue.Dequeue();
}
}
Then we could simply write:
var queue = new Queue<int>(new []{0,1,2,3});
mock.Setup(m => m.BarAsync()).Returns(queue.DequeueAsync);
Or would could make use of the AsyncQueue class from Microsoft.VisualStudio.Threading, which would allow us to do this:
var queue = new AsyncQueue<int>(new []{0,1,2,3});
mock.Setup(m => m.BarAsync()).Returns(queue.DequeueAsync);
The main problem that causes all of this, as that when the end of a setup sequence has been reached, the method is treated as not being setup. To avoid this, you are expected to also call a standard Setup if results should be returned after the end of the sequence has been reached.
I have put together a fairly comprehensive fiddle regarding this functionality with examples of the errors you may encounter when doing things wrong, as well as examples of several different ways you can do things correctly.
https://dotnetfiddle.net/KbJlxb
Moq uses the builder pattern, setting up the behavior of the mocks.
You can, but don't have to use the fluent interface.
Keeping that in mind, I solved the problem this way:
var sequence = myMock
.SetupSequence(""the method I want to set up"");
foreach (var item in stuffToReturn)
{
sequence = sequence.Returns(item);
}
I'm tring to use a lambda with a multiple-params function but Moq throws this exception at runtime when I attempt to call the mock.Object.Convert(value, null, null, null); line.
System.Reflection.TargetParameterCountException: Parameter count mismatch
The code is:
var mock = new Mock<IValueConverter>();
mock.Setup(conv => conv.Convert(It.IsAny<Object>(), It.IsAny<Type>(),
It.IsAny<Object>(), It.IsAny<CultureInfo>())).Returns((Int32 num) => num + 5);
var value = 5;
var expected = 10;
var actual = mock.Object.Convert(value, null, null, null);
What is the proper way to implement it?
It's your Returns clause. You have a 4 parameter method that you're setting up, but you're only using a 1 parameter lambda. I ran the following without issue:
[TestMethod]
public void IValueConverter()
{
var myStub = new Mock<IValueConverter>();
myStub.Setup(conv => conv.Convert(It.IsAny<object>(), It.IsAny<Type>(), It.IsAny<object>(), It.IsAny<CultureInfo>())).
Returns((object one, Type two, object three, CultureInfo four) => (int)one + 5);
var value = 5;
var expected = 10;
var actual = myStub.Object.Convert(value, null, null, null);
Assert.AreEqual<int>(expected, (int) actual);
}
No exceptions, test passed.
Not an answer for OP but perhaps for future googlers:
I had a Callback that didn't match the signature of the method being setup
Mock
.Setup(r => r.GetNextCustomerNumber(It.IsAny<int>()))
.Returns(AccountCounter++)
.Callback<string, int>(badStringParam, leadingDigit =>
{
// Doing stuff here, note that the 'GetNextCustomerNumber' signature is a single int
// but the callback unreasonably expects an additional string parameter.
});
This was the result of some refactoring and the refactoring tool of course couldn't realise that the Callback signature was incorrect
Perhaps it's because you are passing null but It.IsAny<Object>() is expecting any object except null? What happens if you do the following?:
var actual = mock.Object.Convert(value, new object(), typeof(object), CultureInfo.CurrentCulture);
This is just a stab in the dark from me, I'm more familiar with Rhino.Mocks.
My 2nd guess:
Having looked at the Moq.chm that comes with the download,
You are using the Setup(Expression<Action<T>>) method which "Specifies a setup on the mocked type for a call to a void method."
You want te Setup<TResult>(Expression<Func<T,TResult>>) method that "Specifies a setup on the mocked type for a call to a value returning method".
So you could try:
mock.Setup<Int32>(
conv => {
conv.Convert(
It.IsAny<Object>(),
It.IsAny<Type>(),
It.IsAny<Object>(),
It.IsAny<CultureInfo>());
return num + 5;
});
In my case, I thought that the type in Returns<> is the output type, but in fact it was the input type(s).
So if you have a method
public virtual string Foo(int a, int b) { ... }
The correct clause is .Returns<int, int>(...), NOT .Returns<string>(...) which is what I thought initially.
My mistake was because I was testing a function with the same input and return type initially - for example public virtual string Foo(string a).