I'm trying to unit test a method where a function is called in a loop. One of the parameters supplied to the method is a List<string>, declared outside the loop, that should be updated by each call that it is passed to.
I've been trying to mock this behaviour using some examples that I found on SO that involve updating the parameter inside of a Callback(), but this hasn't worked for me as expected.
Here is a short-hand example of the problem I'm having:
Method
public async Task DoSomething() {
var strings = new List<string>();
for(i = 0; i < 2; i++) {
var response = await _responder.GetResponse(i, strings);
//method adds a new string into the collection on each call
}
}
So to test this, I would need to mock both method calls, knowing that the string collection would be empty on one and contain one element on the other...
Test
public async Task TestDoSomething() {
var strings = new List<string>();
var mock = new Mock<Responder>();
mock.Setup(x => x.GetResponse(0, strings)) //mocks first iteration of loop
.ReturnsAsync(new Response())
.Callback<int, List<string>>((number, stringCollection) => {
stringCollection = new List<string> {"addedString"}; //this is where the problem occurs
strings = stringCollection;
});
mock.Setup(x => x.GetResponse(1, strings)) //mocks second iteration of loop
.ReturnsAsync(new Response());
//...
}
So at the point where I try to update the collection of strings inside the callback, studio highlights the parameter and gives me the warning The value passed to the method is never used because it is overwritten in the method body before being read.
The test fails because the setups are not matched, and trying to debug causes the test to crash and drop out.
Can anyone point me in the right direction here? Between the warning message and the fact that all the other examples of this stuff just use Returns rather than ReturnsAsync, I would guess that it's to do with the timing of updating the parameter.
Thanks in advance!
Not sure what exactly you want to test the method call or that values added to the collection.
But if you want to test that method was called, you can use Verify function like this -
mock.Verify(mock => mock.GetResponse(It.IsAny<int>(), strings), Times.Exactly(2));
PS. You should use It.IsAny<int>() cause first param obtain index from loop SO _responder.GetResponse(0, strings) calls only once and so on.
trying to mock one method in repository which having return IQueryable.
Please see the unit test method
[Fact]
public void TestMethod()
{
var mockZonal = new Mock<IBaseRepository<ZonalDefinition>>().SetupAllProperties();
var list = new List<ZonalDefinition>() { new ZonalDefinition() { DestinationZone = "401" } }.AsQueryable();
mockZonal.Setup(r => r.GetQueryableFromSql<ZonalDefinition>(new SqlQuerySpec(), new FeedOptions())).Returns(()=>list);
_repoFactory.Setup(r => r.GetGenericRepository<ZonalDefinition>(It.IsAny<string>(), It.IsAny<string>())).Returns(mockZonal.Object);
var afShipmentDetail = new AirFreightShipmentDetail();
var response = _quoteRespository.SetCXShipmentTargetValue(afShipmentDetail);
Assert.NotNull(response);
}
while executing the test am getting the result for mocked method 'GetQueryableFromSql' as 'Enumeration yielded no results'
enter image description here
As far as I understand Moq, you have to setup your method differently:
mockZonal.Setup(r => r.GetQueryableFromSql<ZonalDefinition>(It.IsAny<SqlQuerySpec>(),
It.IsAny<FeedOptions>()))
.Returns(()=>list);
The way you set it up, it would only match if those exact objects were passed to the method (which they won't).
If you need to be more specific with regards to the parameters to match, have a look at the documentation.
I have following code:
if (ActiveApplication.GetField("previous_date").Value != ActiveApplication.GetField("new_date").Value)
{
//do something..
}
I want to unit test this. Being new to Rhino tests, I am trying to figure out how to pass value so that i go in the loop. Here is what i have tried:
var previous_date = MockRepository.GenerateMock<IField>();
stubApplication.Stub(x => x.GetField("previous_date")).Return(previous_date);
previous_date.Stub(x => x.GetInternalValue()).Return("20160525");
var new_date = MockRepository.GenerateMock<IField>();
stubApplication.Stub(x => x.GetField("new_date")).Return(new_date);
new_date.Stub(x => x.GetInternalValue()).Return("20160525");
Can someone please tell me what am i doing wrong?
This returns previous_date, an interface of type IField:
stubApplication.Stub(x => x.GetField("previous_date")).Return(previous_date)
Because it's not a base class implementation, your code uses the Value property on the interface which has to be setup in a mock as well, rather than using GetInternalValue(). Same with new_stub.
EDIT: You need essentially to do the following (note I'm not sure if this is the correct syntax as I haven't used that framework, but I'm trying to capture the essence):
previous_date.Stub(x => x.Value).Return("20160525");
I've written a piece of code that is responsible for creating an Issue.It uses a visitor pattern to set the Issue assignee.
Here's the code :
public Issue CreateIssue(IssueType type, string subject, string description, Priority priority, string ownerId)
{
var issue = new Issue
{
...
};
IssueManagerContext.Current.IssueAssignmentMethodResolver(type).Visit(issue);
...
return issue;
}
I would like to test the functionality of this code thus somehow I need to mock the behavior of a visitor. After studying different Mock libraries I decided to use Moq.
But I don't know how should I build a mock object that gets an argument from my code instead of hard coding it as it's shown in the quick start guide.
Here's what I have done so far :
var visitor = new Mock<IIssueVisitor>();
visitor.Setup(x => x.Visit(null));
You can only match a specific instance of an object if the test has the same reference as the SUT. The problem in your scenario is that your SUT creates the instance issue, and returns it at the end of the method. Your test cannot access it while the method is executing, which precludes your mock object from being able to match it.
You can configure your mock object to match any Issue instance with the following syntax:
visitor.Setup(x => x.Visit(It.IsAny<Issue>()));
You can also configure the mock to conditionally match an Issue instance:
// Matches any instance of Issue that has an ID of 42
visitor.Setup(x => x.Visit(It.Is<Issue>(theIssue => theIssue.ID == 42)));
If you want to match the reference of a specific instance of Issue, then you'll have to move the instantiation logic into some kind of abstraction (e.g., a factory) of which your test could provide a fake implementation. For example:
// In SUT
var issue = issueFactory.CreateIssue();
...
// In test
var stubIssue = new Issue{ ... };
var issueFactory = new Mock<IIssueFactory>();
var visitor = new Mock<IIssueVisitor>();
...
issueFactory.Setup(factory => factory.CreateIssue())
.Returns(stubIssue);
visitor.Setup(x => x.Visit(stubIssue));
Use the following syntax:
interface IFoo
{
int Bar(string baz);
}
var mock = new Mock<IFoo>();
mock.Setup(x => x.Bar(It.IsAny<string>()))
.Returns((string baz) => 42 /* Here baz contains the value your code provided */);
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);
}