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");
Related
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));
I've been reviewing FluentValidation which is a nice validation library by the way but I noticed that they pass LambdaExpression in instead of an object property and I like to learn the advantage of this usage:
using FluentValidation;
public class CustomerValidator: AbstractValidator<Customer> {
public CustomerValidator() {
RuleFor(customer => customer.Surname).NotEmpty();
RuleFor(customer => customer.Forename).NotEmpty().WithMessage("Please specify a first name");
RuleFor(customer => customer.Company).NotNull();
RuleFor(customer => customer.Discount).NotEqual(0).When(customer => customer.HasDiscount);
RuleFor(customer => customer.Address).Length(20, 250);
RuleFor(customer => customer.Postcode).Must(BeAValidPostcode).WithMessage("Please specify a valid postcode");
}
private bool BeAValidPostcode(string postcode) {
// custom postcode validating logic goes here
}
}
Customer customer = new Customer();
CustomerValidator validator = new CustomerValidator();
ValidationResult results = validator.Validate(customer);
bool validationSucceeded = results.IsValid;
IList<ValidationFailure> failures = results.Errors;
As you can see RuleFor(customer => customer.Surname).NotEmpty(); instead, RuleFor(customer.Surname).NotEmpty(); wouldn't be enough and clean?
instead, RuleFor(customer.Surname).NotEmpty(); wouldn't be enough and clean?
No. Because at the time when you're calling RuleFor, you don't have a customer - therefore you can't access their surname.
As is usually the case with delegates, you're passing around code to be executed at a later time. The expression customer.Surname is an expression which would be evaluated immediately in the context of an existing customer variable.
Now if we had the mythical infoof operator, we could do it without creating a delegate. We could potentially write something like:
RuleFor(infoof(Customer.Surname)).NotEmpty()
which would be lovely. The RuleFor method would take that property reference and evaluate it later against a given customer. Wonderful.
Unfortunately, we don't have that operator - so the easiest way of expressing the idea of "when you've got a customer, get hold of the Surname property" is to use a delegate. It's also very flexible, as it can work with (almost) any code you want to execute.
If you were to pass customer.SurName, you would be pointing to the value of the SurName property of a specific customer instance. Using a lambda function allows the validation logic to take a customer object when the validation logic is invoked, and then retrieve the SurName property of that customer.
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
Say I have a very simple entity like this:
public class TestGuy
{
public virtual long Id {get;set;}
public virtual string City {get;set;}
public virtual int InterestingValue {get;set;}
public virtual int OtherValue {get;set;}
}
This contrived example object is mapped with NHibernate (using Fluent) and works fine.
Time to do some reporting. In this example, "testGuys" is an IQueryable with some criteria already applied.
var byCity = testGuys
.GroupBy(c => c.City)
.Select(g => new { City = g.Key, Avg = g.Average(tg => tg.InterestingValue) });
This works just fine. In NHibernate Profiler I can see the correct SQL being generated, and the results are as expected.
Inspired by my success, I want to make it more flexible. I want to make it configurable so that the user can get the average of OtherValue as well as InterestingValue. Shouldn't be too hard, the argument to Average() seems to be a Func (since the values are ints in this case). Easy peasy. Can't I just create a method that returns a Func based on some condition and use that as an argument?
var fieldToAverageBy = GetAverageField(SomeEnum.Other);
private Func<TestGuy,int> GetAverageField(SomeEnum someCondition)
{
switch(someCondition)
{
case SomeEnum.Interesting:
return tg => tg.InterestingValue;
case SomeEnum.Other:
return tg => tg.OtherValue;
}
throw new InvalidOperationException("Not in my example!");
}
And then, elsewhere, I could just do this:
var byCity = testGuys
.GroupBy(c => c.City)
.Select(g => new { City = g.Key, Avg = g.Average(fieldToAverageBy) });
Well, I thought I could do that. However, when I do enumerate this, NHibernate throws a fit:
Object of type 'System.Linq.Expressions.ConstantExpression' cannot be converted to type 'System.Linq.Expressions.LambdaExpression'.
So I am guessing that behind the scenes, some conversion or casting or some such thing is going on that in the first case accepts my lambda, but in the second case makes into something NHibernate can't convert to SQL.
My question is hopefully simple - how can my GetAverageField function return something that will work as a parameter to Average() when NHibernate 3.0 LINQ support (the .Query() method) translates this to SQL?
Any suggestions welcome, thanks!
EDIT
Based on the comments from David B in his answer, I took a closer look at this. My assumption that Func would be the right return type was based on the intellisense I got for the Average() method. It seems to be based on the Enumerable type, not the Queryable one. That's strange.. Need to look a bit closer at stuff.
The GroupBy method has the following return signature:
IQueryable<IGrouping<string,TestGuy>>
That means it should give me an IQueryable, all right. However, I then move on to the next line:
.Select(g => new { City = g.Key, Avg = g.Average(tg => tg.InterestingValue) });
If I check the intellisense for the g variable inside the new { } object definition, it is actually listed as being of type IGrouping - NOT IQueryable>. This is why the Average() method called is the Enumerable one, and why it won't accept the Expression parameter suggested by David B.
So somehow my group value has apparently lost it's status as an IQueryable somewhere.
Slightly interesting note:
I can change the Select to the following:
.Select(g => new { City = g.Key, Avg = g.AsQueryable<TestGuy>().Average(fieldToAverageBy) });
And now it compiles! Black magic! However, that doesn't solve the issue, as NHibernate now doesn't love me anymore and gives the following exception:
Could not parse expression '[-1].AsQueryable()': This overload of the method 'System.Linq.Queryable.AsQueryable' is currently not supported, but you can register your own parser if needed.
What baffles me is that this works when I give the lambda expression to the Average() method, but that I can't find a simple way to represent the same expression as an argument. I am obviously doing something wrong, but can't see what...!?
I am at my wits end. Help me, Jon Skeet, you're my only hope! ;)
You won't be able to call a "local" method within your lambda expression. If this were a simple non-nested clause, it would be relatively simple - you'd just need to change this:
private Func<TestGuy,int> GetAverageField(SomeEnum someCondition)
to this:
private Expression<Func<TestGuy,int>> GetAverageField(SomeEnum someCondition)
and then pass the result of the call into the relevant query method, e.g.
var results = query.Select(GetAverageField(fieldToAverageBy));
In this case, however, you'll need to build the whole expression tree up for the Select clause - the anonymous type creation expression, the extraction of the Key, and the extraction of the average field part. It's not going to be fun, to be honest. In particular, by the time you've built up your expression tree, that's not going to be statically typed in the same way as a normal query expression would be, due to the inability to express the anonymous type in a declaration.
If you're using .NET 4, dynamic typing may help you, although you'd pay the price of not having static typing any more, of course.
One option (horrible though it may be) would be try to use a sort of "template" of the anonymous type projection expression tree (e.g. always using a single property), and then build a copy of that expression tree, inserting the right expression instead. Again, it's not going to be fun.
Marc Gravell may be able to help more on this - it does sound like the kind of thing which should be possible, but I'm at a loss as to how to do it elegantly at the moment.
Eh? the parameter to Queryable.Average is not Func<T, U>. It's Expression<Func<T, U>>
The way to do this is:
private Expression<Func<TestGuy,int>> GetAverageExpr(SomeEnum someCondition)
{
switch(someCondition)
{
case SomeEnum.Interesting:
return tg => tg.InterestingValue;
case SomeEnum.Other:
return tg => tg.OtherValue;
}
throw new InvalidOperationException("Not in my example!");
}
Followed by:
Expression<Func<TestGuy, int>> averageExpr = GetAverageExpr(someCondition);
var byCity = testGuys
.GroupBy(c => c.City)
.Select(g => new { City = g.Key, Avg = g.Average(averageExpr) });
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.