I'm using the built-in C# unit-testing classes like Assert and CollectionAssert. I want to test that all objects returned by a method call have a certain value on a given property.
Are there special classes provided for unit testing this kind of thing, or would I just use the normal collection methods and feed the results into a regular Assert call?
e.g. does something like this exist: Assert.TrueForAll(myList,x => x.Prop == 123)
How about returning the check?
mylist.ForEach(x => Assert.IsTrue(x.Prop == 123));
Related
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.
I am trying to use moq to mock a function on my licence class.
The licence class has the following interface:
Licence TryGetLicence(Predicate<Licence> filter);
In my integration test I am using mef to lazy load objects. My class finds the mef loaded objects and needs to check if there are licences available. For my test I create two objects, one of which can be licenced. I want to use moq to only return a licence for this object and null for the other, just as the real class would. The problem I am having is that moq doesn’t like me passing in a predicate. I’m not sure if moq just doesn’t handle predicates in this way or am I just implementing this wrong?
Here are the lines of code I have in my test that sets up moq for the above interface:
var lic = new Licence
{
LicId = Guid.Parse("53024D4E-3A01-4489-A341-753D04748EB9"),
LicName = "test",
Count = 1,
ExpiryDate = DateTime.Now.AddDays(2)
};
var mockAgent = new Mock<ILicenceAgent>();
mockAgent.Setup(x => x.TryGetLicence (y => y.LicId == lic.LicId)) Returns(lic);
This builds but when the last line is hit it throws an Unsupported expression exception.
For other tests I have used:
mockAgent.Setup(x => x. TryGetLicence (It.IsAny<Predicate<Licence>>())).Returns(lic);
I can’t use this for my new test as it would return a valid licence for both objects I have loaded.
Can moq be used in the way I am trying to use it?
This should solve the problem:
Predicate<Licence> predicate = y => y.LicId == lic.LicId;
mockAgent.Setup(x => x.TryGetLicence (predicate)).Returns(lic);
When you create the predicate inside Setup call, lambda expression is evaluated as a part of the expression that will be passed as a parameter. We prevent that by making sure it's only a delegate on the line above.
If you have 2 licences - lic1 and lic2, you can setup mock like this:
mockAgent.Setup(x => x.TryGetLicence(It.Is<Predicate<Licence>>(/* add your specific condition for licence1 */ ))).Returns(lic1);
mockAgent.Setup(x => x.TryGetLicence(It.Is<Predicate<Licence>>(/* add your specific condition for licence2 */ ))).Returns(lic2);
I'm using mongo driver, and trying to fake results of any to test whether Insert or Update was called based on results.
Here's piece of code I think relevant:
_context = _collection.AsQueryable();
if (_context.Any(s => s.Id == id))
{
...
after that I'm calling either _collection.Update() or _collection.Insert().
Here's what I tried so far with the unit test:
var collectionMock = new Mock<MongoCollection<Storage>>();
var queriableMock = new Mock<IQueryable<Storage>>();
queriableMock.Setup(q => Enumerable.Any(q)).Returns(() => false);
...
collectionMock.Setup(c => c.AsQueryable()).Returns(() => queriableMock.Object);
collectionMock.Setup(c => c.Save(It.IsAny<Storage>()));
I'm getting exception
"Expression references a method that does not belong to the mocked
object: q => q.Any()"
The Setup method takes a lambda that is not executed but is interpreted so that the mock can identify methods/properties of the mock object that will be called during the test and what should be returned/thrown/called back/etc.
Moq doesn't know the implementation of Enumerable.Any<T>(this T item), and therefore cannot figure out what methods or properties of T will be accessed or what they should do/return.
Therefore, in order to mock a call to Enumerable.Any, you need to identify what methods/properties of your object it, in turn, calls, and then mock those.
You can find the implementation here. Simply follow the call path and mock out everything Any needs to call.
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.
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();