Moq Setup does not work as expected in a separate class - c#

I am using moq version 4.2 to unit test some controllers of web api 2 with EF as the ORM. Since a lot of tests need a mocked IEntityRepository<User> so I use a static method in a separate class called TestHelper to create such a fake repository so that I can just call this method in all the tests where needed. Here is the static method:
internal static IEntityRepository<User> GetSingleUserMockRepository(User user, bool noTracking = true, params Expression<Func<User, object>>[] properties)
{
var userRepository = new Mock<IEntityRepository<User>>();
if (properties.Any())
userRepository.Setup(x => x.GetSingleInclude(user.Key, noTracking, properties)).Returns(Task.FromResult(user));
else
userRepository.Setup(x => x.GetSingle(user.Key, noTracking)).Returns(Task.FromResult(user));
return userRepository.Object;
}
I am not showing other method details here because don't think they're relevant to my problem. The thing is when calling this static method in my tests and pass the returned user repository into controllers the test will fail because it cannot find the user i.e. Setup didn't work!. However, if I repeat the test implementation within my tests to create the mock repository as a local variable; everything works fine.
Namely, this doesn't work (where Devices is a navigation property on the User entity, again don't think the detail matters here) e.g. if I pass the returned userRepository into my controller the test will fail.:
var userRepository = TestHelper.GetSingleUserMockRepository(user, true, x=> x.Devices);
But this works e.g. if I just use a local variable in the test and pass the userRepository.Object into my controller everything works as expected:
var userRepository = new Mock<IEntityRepository<User>>();
userRepository.Setup(x => x.GetSingleInclude(user.Key, true, u => u.Devices)).Returns(Task.FromResult(user));
Can someone please explain why? I thought these two ways are equivalent but clearly not in practice.

This is maybe not a full answer (yet), but still to long to fit into a Stack Overflow comment.
When you do:
userRepository.Setup(x => x.GetSingleInclude(user.Key, noTracking, properties)).Returns(...);
you are saying: When GetSingleInclude is called with that user.Key and that noTracking and in particular that properties which is an array of expression trees, Moq shall return what you specify.
However, if Moq gets a call to GetSingleInclude where one or more of the arguments are not equal to the values you supplied, your setup is not relevant, and Moq returns instead the default value which is null.
(If you had used MockBehavior.Strict instead, it would have thrown an exception instead of silently just returning null, which could be more helpful for understanding the issue.)
So when are two arrays of expression trees equal? If Moq uses the default equality comparer for arrays, they are only "equal" when they are the same array instance. If Moq uses some entry-wise comparison, it will come down to whether each expression tree is equal as reference (i.e. same Expression<> instance). In any case you may have trouble.
The question is why it works in the other case. Does GetSingleInclude have special overloads for when the number of properties (expression trees) is little?
What is the result of running the code from this question?
I am saying that you may be facing the same problem as in the thread
Mocking and verifying call to method containing an Expression<Func<T,bool>> parameter.

Related

Mocking the NHibernate JoinAlias with Moq

I have the following repository code that will return a Company object based on an ID value, searching across the standard Company table and an additional table named ExternalCompany.
public Company FindByIdJoin(long id)
{
ExternalCompany xcomp = null;
return Session.QueryOver<Company>()
.Where(p => p.ObjectId == id)
.JoinAlias(p => p.ExternalCompanies, () => xcomp, JoinType.LeftOuterJoin)
.SingleOrDefault<Company>();
}
The code returns values that I expect. However, the trouble I'm having is in writing a Moq unit test to handle the JoinAlias call.
In a simpler method, called FindById, the code is essentially the same except there is no line for JoinAlias. The unit test for this simpler method is:
[Test]
public void FindById_returns_Company_for_valid_Id()
{
// Arrange
Mock<IQueryOver<Company, Company>> mockQueryOver = new Mock<IQueryOver<Company, Company>>();
mockQueryOver.Setup(x => x.Where(It.IsAny<Expression<Func<Company, bool>>>())).Returns(mockQueryOver.Object);
mockQueryOver.Setup(x => x.SingleOrDefault()).Returns(fake_Company);
// Act
var result = _repository.FindById(fake_Company.ObjectId);
// Assert
Assert.IsNotNull(result);
mockQueryOver.VerifyAll();
}
This test works and passes without a problem (fake_Company and _repository are defined elsewhere).
The problem is trying to put a test together for the FindByIdJoin call. I have tried using an additional Setup line like this (which goes between the Where and SingleOrDefault Setup lines):
mockQueryOver.Setup(x => x.JoinAlias(It.IsAny<Expression<Func<Company>>>(), It.IsAny<Expression<Func<ExternalCompany>>>(), JoinType.LeftOuterJoin)).Returns(mockQueryOver.Object);
The system tells me that "the best overloaded method match for IQueryOver ... has some invalid arguments."
So, I tried a few other variations on the Setup, but could not find a workable pattern.
My question is: what Setup arguments will work for JoinAlias so that I can properly test the FindByIdJoin method? Thanks!
The particular overload of JoinAlias you are using is
IQueryOver<TRoot, TSubType> JoinAlias(
Expression<Func<TSubType, object>> path,
Expression<Func<object>> alias,
JoinType joinType);
So, your setup needs to match this. Based on how you setup your IQueryOver mock, the correct setup would then be
mockQueryOver.Setup(x => x.JoinAlias(
It.IsAny<Expression<Func<Company, object>>>(),
It.IsAny<Expression<Func<object>>>(),
JoinType.LeftOuterJoin))
.Returns(mockQueryOver.Object);
Shouldn't MOQ be used for behaviour tests? Such Data access tests seem to be state dependent and I think using mock objects for such a system under test is an overkill.

How to Moq NHibernate extension methods?

I'm developing an application using NHibernate for the ORM, NUnit for unit testing and Ninject for my DI. I'm mocking the ISession like so:
var session = new Mock<ISession>();
With the regular non-mocked session objects I can query them with LINQ extension methods like this:
var result = Session.Query<MyEntity>();
But when I try to mock this with the following code...
session.Setup(s => s.Query<MyEntity>());
...I get a runtime "Not supported" exception:
Expression references a method that does not belong to the mocked object: s => s.Query<MyEntity>()
How can I mock basic queries like this in Moq/NHibernate?
Query<T>() is an extension method, that's why you can't mock it.
Although #Roger answer is the way to go, sometimes it's useful to have specific tests. You can start investigating what Query<T>() method does - either by reading the NHibernate code, or using your own tests, and set the appropriate methods on ISession.
Warning: creating such a setup will make your test very fragile, and it will break, if the internal implementation of NHibernate changes.
Anyway, you can start your investigation with:
var mockSession = new Mock<ISession>(MockBehavior.Strict); //this will make the mock to throw on each invocation which is not setup
var entities = mockSession.Object.Query<MyEntity>();
The second line above is going to throw an exception and show you which actual property/method on ISession the Query<T>() extension method tries to access, so you can set it accordingly. Keep going that way, and eventually you will have a good setup for your session so you can use it in the test.
Note: I'm not familiar with NHibernate, but I have used the above approach when I had to deal with extension methods from other libraries.
UPDATE for version 5:
In the new NHibernate versions Query<T> is part of the ISession interface, not an extension function, so it should be easy to mock.
Old answer:
I tried Sunny's suggestion and got this far but got stuck since the IQuery is cast to an NHibernate.Impl.ExpressionQueryImpl which is internal and I don't think can be extended. Just posting this to save other lost souls a couple hours.
var sessionImplMock = new Mock<NHibernate.Engine.ISessionImplementor>(MockBehavior.Strict);
var factoryMock = new Mock<NHibernate.Engine.ISessionFactoryImplementor>(MockBehavior.Strict);
var queryMock = new Mock<IQuery>(MockBehavior.Strict);//ExpressionQueryImpl
sessionImplMock.Setup(x => x.Factory).Returns(factoryMock.Object);
sessionImplMock.Setup(x => x.CreateQuery(It.IsAny<IQueryExpression>())).Returns(queryMock.Object);
sessionMock.Setup(x => x.GetSessionImplementation()).Returns(sessionImplMock.Object);

Sequence contains no elements when mocking repository

I'm trying to mock the repository code below:
var simulatorInstance = bundleRepository
.FindBy<CoreSimulatorInstance>(x => x.CoreSimulatorInstanceID == instanceID)
.Single();
but I get an error that states the "Sequence contains no elements". I tried changing the .Single to SingleOrDefault, but that returns a null.
In my unit test I mocked my the repository using the following:
This does not work
this.mockedRepository.Setup(
x => x.FindBy<CoreSimulatorInstance>(
z => z.CoreSimulatorInstanceID == 2))
.Returns(coreSimulatorInstancesList.AsQueryable());
This work for now using the Is.Any because I only have one record
this.mockedRepository.Setup(
x => x.FindBy<CoreSimulatorInstance>(
It.IsAny<Expression<Func<CoreSimulatorInstance, bool>>>()))
.Returns(coreSimulatorInstancesList.AsQueryable());
I want to mock the code using the .Single.
My guess is that you're using Moq to setup the repository's FindBy method so that business logic code hits the mocked method when you're running your test.
I think that the issue is that Moq is unable to match the parameter you provided during the mock setup with the parameter you provide during the execution of your business logic code, resulting in your mocked repository method not being executed and coreSimulatorInstancesList not being returned.
Since the parameter you provided to Moq during setup is an expression
z => z.CoreSimulatorInstanceID == 2
even when your business logic code executes with instanceID of 2
x => x.CoreSimulatorInstanceID == instanceID
resulting in an expression that is equivalent to the one you setup in the mock, they are still not matched because they are different expressions. These are two different expression objects. I don't think there's a way for Moq to know that they are equivalent and match your mocked method based on that.
I would go with Is.Any approach. If you want to be more thorough I think you would need to hand build a custom fake repository class in this case.

Using Mock objects with Dictionary

I just started working with Unit Testing with NMock
I one my test cases involve adding an entry in a dictionary which is then passed to the unit being tested. I define the map as:
var item = new Mock<MyClass>().Object;
var myMap = new Dictionary<MyClass, IList<MyOtherClass>>
{
{ item, completionRequirement }
};
However when I do a myMap.ContainsKey(item) inside the unit being tested it returns false.
I am able to view a proxied item in the Dictionary on inspecting it. I am guessing that I need to do something else as well on the mocked item.(Most probably define .Equals(object o)).
My question is :
How do you define the Equals(object o) for the mocked item.
Or is there a different solution to the problem altogether.
You might want to mock the dictionary as well. That is, refactor to use IDictionary<MyClass,IList<MyOtherClass>, then pass in a mocked dictionary. You can then set up expectations so that it returns mocked objects as necessary.
It's also possible that you may not need to use a mock at all in this instance. It's not possible to tell from what you've given us, but I've often found that people new to mocking can sometimes forget that you can use the real objects as well if those objects don't have cascading dependencies. For example, you don't really need to mock a class that's just a simple container. Create one and use it, instead. Just something to think about.
The approach given at http://richardashworth.blogspot.com/2011/12/using-reflection-to-create-mock-objects.html is in Java, but presents another approach to this problem using Reflection.
I like the idea of setting up a 'fake' object along the lines of what tvanfosson is suggesting.
But if you want to do it with a mocking framework, I think all you need to do is setup an expectation for what item.Object should be. In Rhino Mocks the syntax would be something like:
var knownObject = "myKey";
var mock = MockRepository.GenerateStub<IMyClass>();
mock.Stub(x=>x.Object).Return(knownObject);
That said, I have no idea what the equivalent code would be in NMocks, but it shouldn't be hard to figure it out if you're working with it (you can always ask a question on the user group).
HTH

Newbie question about mocking and moq framework

I've been using Moq framework in c# for mocking in unit tests however there is one thing I dont complete understand yet. I have this line of code
var feedParserMock = new Mock<ApplicationServices.IFeedParser>();
feedParserMock.Setup(y => y.ParseFeed(csv)).Returns(items).Verifiable();
The second line does it mean it will only return the value if the parameter passed is the same? because the parameter that I pass to ParseFeed inside my controller is build inside the controller and I dont have access to it in the unit test. Currently the method is returning null, is there any way to specify I want to return my items variable no matter what the parameter is?
Yes. Moq provides the It static class that has helper methods for specifying parameters that satisfy certain criteria. Your example could be:
feedParserMock.Setup(y => y.ParseFeed(It.IsAny<string>())).Returns(items).Verifiable();
Then Moq will match your setup, given that the parameter is of the specified type and non-null (I chose string here, you should of course replace that with the correct type of your parameter in order for the code to compile).
You can also pass a delegate that Moq will evalute in order to determine if the setup is a match. Example:
feedParserMock.Setup(y => y.ParseFeed(It.Is<string>(s => s.Length > 3));
This will match any method invocations on ParseFeed, where the parameter is a string with a Length larger than 3.
Check out the "Matching arguments" section of the Moq Quickstart guide to learn more.
Yes, you can Use It.IsAny()
for example
feedParserMock.Setup(y => y.ParseFeed(It.IsAny<string>())).Returns(items).Verifiable();

Categories