How to Setup/Verify method call with specified parameter - c#

I need to test if method GetKey(object target) was called with specified parameter. I know that verification can be called like
processor.Verify(x => x.GetKey(It.Is<object>(y => y == target)));
but how should setup look?
processor.Setup(x => x.GetKey(It.Is<object>(y => y == target)));
or
processor.Setup(x => x.GetKey(It.IsAny<object>()));
What is the difference in these 2 setups? Does it really matter in this case?
The processor interface:
public interface ILayoutProcessor
{
object GetKey(object target);
}

Just pass the specified parameter in the Setup or Verify method expression
processor.Setup(x => x.GetKey(target)).Verifiable();
and verify later
processor.Verify();
or
processor.Verify(x => x.GetKey(target), Times.AtLeastOnce);

processor.Setup(x => x.GetKey(It.Is<object>(y => y == target)));
Is a setup for when the method is called with an object matching the specified condition.
processor.Setup(x => x.GetKey(It.IsAny<object>()));
Is a setup that will match any object argument.
In your case, where you want to only verify that the method was called with a certain argument, it does not matter which setup you use. In fact, if the return value of your function is not used, you don't even need a setup to be able to verify. However in your case I assume you do since you mention Callback and Returns in the comments.
Note that you can shorten your verification to simply:
processor.Verify(x => x.GetKey(target));

Related

It.Is condition sets zero [duplicate]

Hi I've been using moq for a while when I see this code.
I have to setup a return in one of my repo.
mockIRole.Setup(r => r.GetSomething(It.IsAny<Guid>(), It.IsAny<Guid>(),
It.IsAny<Guid>())).Returns(ReturnSomething);
I have three parameters and I just saw these in one of articles or blog on the net.
What is the use of It.Is<> or It.IsAny<> for an object? if I could use Guid.NewGuid() or other types then why use It.Is?
I'm sorry I'm not sure if my question is right or am I missing some knowledge in testing.
But it seems like there is nothing wrong either way.
Using It.IsAny<>, It.Is<>, or a variable all serve different purposes. They provide increasingly specific ways to match a parameter when setting up or verifying a method.
It.IsAny
The method set up with It.IsAny<> will match any parameter you give to the method. So, in your example, the following invocations would all return the same thing (ReturnSomething):
role.GetSomething(Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid());
Guid sameGuid = Guid.NewGuid();
role.GetSomething(sameGuid, sameGuid, sameGuid);
role.GetSomething(Guid.Empty, Guid.NewGuid(), sameGuid);
It doesn't matter the actual value of the Guid that was passed.
It.Is
The It.Is<> construct is useful for setup or verification of a method, letting you specify a function that will match the argument. For instance:
Guid expectedGuid = ...
mockIRole.Setup(r => r.GetSomething(
It.Is<Guid>(g => g.ToString().StartsWith("4")),
It.Is<Guid>(g => g != Guid.Empty),
It.Is<Guid>(g => g == expectedGuid)))
.Returns(ReturnSomething);
This allows you to restrict the value more than just any value, but permits you to be lenient in what you accept.
Defining a Variable
When you set up (or verify) a method parameter with a variable, you're saying you want exactly that value. A method called with another value will never match your setup/verify.
Guid expectedGuids = new [] { Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid() };
mockIRole.Setup(r => r.GetSomething(expectedGuids[0], expectedGuids[1], expectedGuids[2]))
.Returns(ReturnSomething);
Now there's exactly one case where GetSomething will return ReturnSomething: when all Guids match the expected values that you set it up with.
If you look at the Quickstart documentation for Moq
Matching Arguments
// any value
mock.Setup(foo => foo.DoSomething(It.IsAny<string>())).Returns(true);
// matching Func<int>, lazy evaluated
mock.Setup(foo => foo.Add(It.Is<int>(i => i % 2 == 0))).Returns(true);
// matching ranges
mock.Setup(foo => foo.Add(It.IsInRange<int>(0, 10, Range.Inclusive))).Returns(true);
// matching regex
mock.Setup(x => x.DoSomething(It.IsRegex("[a-d]+", RegexOptions.IgnoreCase))).Returns("foo");

How to mock a method returning IEnumerable<T> in unit test method?

I have to mock a method which returns IEnumerable as shown below.
public IEnumerable<Program> GetAllPrograms(string marketCode) {
return context.Set<Program>()
.Where(p => p.Market.Equals(marketCode)
&& p.IsEnabled == true);
}
I tried the below approach, but this call does not return any result.
programRepositoryMock.Setup(m => m.GetAllPrograms("ATV"))
.Returns(It.IsAny<IEnumerable<QuoteSettings.Program>>());
Please let me know how to mock this instance?
Note: I want to return data for this mock.
Thanks
The argument to Returns() is the value you want the mock to return. Do not use any constructs from the mocking library in there, but just return what you want:
List<Program> result = new List<Program>();
// Add entries to result list here...
programRepositoryMock.Setup(m => m.GetAllPrograms("ATV"))
.Returns(result);
This will return whatever is in the list when GetAllPrograms("ATV") method is called. You would need the It.IsAny<> construct if you want to filter on the arguments to GetAllPrograms(). The following would match any station name:
programRepositoryMock.Setup(m => m.GetAllPrograms(It.IsAny<string>()))
.Returns(result);

Is there any better way of writing this test with Moq?

I have a private method which is being called in a method I am testing.I want to verify the correct parameters are being passed to this private method. I have written the following setup in Moq which will test what I want, however it doesn't really allow me to follow the Arrange, Act, Assert pattern.
Is there any way I can perform a similar test where by the assert can appear with all of my other asserts? At the moment the code below lives within the Arrange.
myClass.Setup(
x =>
x.myMethod(
It.IsAny<Person>>(),
It.IsAny<string>(),
It.IsAny<Person>(),
It.IsAny<ICollection<string>>(),
It.IsAny<ICollection<string>>(),
It.IsAny<bool>())).Callback
<Person, string, Person, Person, ICollection<string>, bool>(
(a, b, c, d, e, f) =>
{
Assert.AreEqual("NameA", a.Name);
Assert.AreEqual("StringB", b);
Assert.AreEqual("NameC", c.Name);
Assert.AreEqual(2, d);
var dList = d.ToList().OrderBy(x => x.Name);
Assert.AreEqual("PersonA", dList[0].Name)
Assert.AreEqual("PersonB", dList[1].Name);
});
I should say, I am aware that you can perfom a verify to check whether a method has been called with certain inputs, however I am not aware of any way of matching the ICollection params.
If you are using those assertions to check the parameters, you can do it in your setup. If your mock uses strict behavior, it will fail if a parameter doesn't match the predicate.
// declare your mock with strict behavior
myClass.Setup(
x =>
x.myMethod(
It.Is<Person>(person => person.Name == "NameA"),
"Stringb",
It.Is<Person>(person => person.Name == "NameC"),,
It.Is<ICollection<string>>(coll =>{
//your other validations
}),
It.IsAny<ICollection<string>>(),
It.IsAny<bool>()));
Purpose of unit tests is to verify that your class behaves as expected. You should exercise class via its public interface and check following things:
class state changes
returned results
calls to dependencies
Other stuff has no value while class behaves as expected. You can refactor your class and make that private method in-line.

moq and parameters matching

I'm struggeling with using moq and validating parameters passed to the methods of mocked interface. I have a code like:
MockRepository mockRepository = new MockRepository(MockBehavior.Default);
Mock<IConfigurationUpdater> workerInstanceMock = mockRepository.Create<IConfigurationUpdater>();
Mock<IConfiguration> configurationMock = mockRepository.Create<IConfiguration>();
configurationMock.Setup(t => t.Folder).Returns("Folder");
configurationMock.Setup(t => t.FileName).Returns("FileName");
workerInstanceMock
.Setup(
x => x.DoSomeWork(
It.Is<string>(
t => t == Path.Combine(configurationMock.Object.Folder, configurationMock.Object.FileName))))
.Verifiable("DoSomeWork not properly called");
mockRepository.VerifyAll();
The problem is that inside the lambda expresion generated for "It.Is", all properties of configurationMock (which were setup previously) are null. (if I would take that "Path.Combine" into a string, it would all work just fine).
In this exact case, the "Path.Combine" is failing because it received null parameters.
How should I properly use mocks and validate that my interface is called with the correct parameters.
Thanks,
florin
I think you need to use moq properties that will automatically start tracking its value (Stubs).
Instead of:
configurationMock.Setup(t => t.Folder).Returns("Folder");
configurationMock.Setup(t => t.FileName).Returns("FileName");
you can use
configurationMock.SetupProperty(t => t.Folder, "Folder");
configurationMock.SetupProperty(t => t.FileName, "FileName");
and then access the property as you did:
configurationMock.Object.Folder
More on moq properties can be found here: http://code.google.com/p/moq/wiki/QuickStart#Properties

Moq does It.Is<List<List<string>>>(x => x.Count == 10) do what I think it should do?

I am passing this into the constructor of an object I am unit testing
It.Is<List<List<string>>>(x => x.Count == 10)
but when I step into the constructor, this statement resolves to null instead of a a List<List<string>> with a Count of 10. Am I misunderstanding how this works?
The It.Is method is not meant to be called. Actually, I think it should just throw, instead of returning the default value of the type.
It is meant to be used in the expression trees used to setting expectations:
interface IFoo { bool DoSomething(IList<IList<string>> strings); }
var mock = new Mock<IFoo>();
mock.Setup(f => f.DoSomething(It.Is<IList<IList<string>>>(l => l.Count == 10))
.Returns(true);
The example sets up a mock object of IFoo that will return true when passed an IList<IList<string>> object with 10 elements. This means that after the following call, result will be true:
IList<IList<string>> listWith10Elements = // create a list with 10 elements
bool result = mock.Object.DoSomething(listWith10Elements);
If you're passing something into the constructor of an object, you would normally use the proxy object from a mock, with Setup on that mock providing any context which your class needs.
For instance:
var mock = new Mock<List<List<string>>>();
mock.Setup(x => x.Count()).Returns(10);
var myClass = new MyClass(mock.Object);
Use Verify to check interactions. What you have there is a matcher, which you can use in Setup and Verify to match particular types of arguments.
Except, of course, that you won't be able to mock List because it doesn't have the virtual methods you're after. Try using, and mocking, ICollection<List<string>> instead.
I think this should do what you want. Hope this helps.

Categories

Resources