I'm using Moq to write unit tests that use Entity Framework 6 DbSet and DbContext objects. I have a service method with a cascading/multi-level Include and I can't figure out how to set it up for testing. The service method looks something like this:
return DataContext.Cars
.Include(p => p.Model)
.Include(p => p.Model.Make)
.Select(c => new
{
Key = c.CarId,
Value = string.Format("{0} {1} {2}", c.Model.Make.Name, c.Model.Name, c.Trim)
}
).ToArray();
I know that I have to setup the Include to return the mocked object, like this:
mockCarDbSet.Setup(m => m.Include(It.IsAny<string>())).Returns(mockCarSet.Object);
But I'm getting a null reference exception from the cascaded .Include(p => p.Model.Make). How do I set up Moq to handle multiple levels of Include?
EDIT
OK, so it turns out that I can't use It.IsAny<string> for Include calls that use lambdas instead of strings, so now I have two problems:
How do I setup a mock with Include that accepts a lambda?
Will the setup for above cascade to multiple levels?
include() is a static method(extension method).
Moq doesn't support a static methods mock(read this link).
To test your code you need to set your mockCarDbSet to return IQueryable<Car>:
var carQuery = new List<Car>
{
//add cars
}
IQueryable<Post> query = carQuery.AsQueryable();
return query as a result of DataContext.Cars
Those steps will work around the static method problem.
So thanks to #Old Fox reminding me that Moq won't work with static members, I found a way to do this using Microsoft Fakes. Shims allows you to shim static methods. I used Moq to set up Mock<DbSet> objects for each of the entities:
var carData = new List<Car>{new Car{ Trim = "Whatever" }};
var mockCarSet = new Mock<DbSet<Car>>();
mockCarSet.As<IQueryable<Car>>().Setup(m => m.Provider).Returns(carData.Provider);
mockCarSet.As<IQueryable<Car>>().Setup(m => m.Expression).Returns(carData.Expression);
mockCarSet.As<IQueryable<Car>>().Setup(m => m.ElementType).Returns(carData.ElementType);
mockCarSet.As<IQueryable<Car>>().Setup(m => m.GetEnumerator()).Returns(carData.GetEnumerator);
var mockMakeSet = new Mock<DbSet<Make>>();
//do the same stuff as with Car for IQueryable Setup
var mockModelSet = new Mock<DbSet<Model>>();
//do the same stuff as with Car for IQueryable Setup
using(ShimsContext.Create())
{
//hack to return the first, since this is all mock data anyway
ShimModel.AllInstances.MakeGet = model => mockMakeSet.Object.First();
ShimCar.AllInstances.ModelGet = car => mockModelSet.Object.First();
//run the test
}
Related
I am trying to unit test the following method (repo is mocked):
public List<StatusLevelDTO> FindAllTranslated(string locale)
{
var statusLevels = Context.StatusLevels
.IncludeFilter(sl => sl.Translations
.Where(t => t.Locale.Name == locale))
.Where(sl => !sl.Deleted)
.ToList();
return Mapper.Map<List<StatusLevelDTO>>(statusLevels);
}
It uses a 3rd party library called EntityFramework Plus which I believe uses projection to filter included entities.
Now, when I run the whole project, everything is fine, but unit test seems to ignore this method and returns everything.
Is there any way to make IncludeFilter extension method simply do its work?
Mock configuration:
public static DbSet<T> GetMockedDbSet<T>(List<T> sourceList) where T : class
{
var queryableList = sourceList.AsQueryable();
var dbSetMock = new Mock<DbSet<T>>();
dbSetMock.As<IQueryable<T>>().Setup(x => x.GetEnumerator()).Returns(() => queryableList.GetEnumerator());
dbSetMock.As<IQueryable<T>>().Setup(m => m.Provider).Returns(queryableList.Provider);
dbSetMock.As<IQueryable<T>>().Setup(m => m.Expression).Returns(queryableList.Expression);
dbSetMock.As<IQueryable<T>>().Setup(m => m.ElementType).Returns(queryableList.ElementType);
dbSetMock.Setup(d => d.Add(It.IsAny<T>())).Callback<T>(s => sourceList.Add(s));
dbSetMock.Setup(d => d.Include(It.IsAny<string>())).Returns(dbSetMock.Object);
return dbSetMock.Object;
}
A possible duplicate, e.g. Mocking Extension Methods with Moq doesn't answer my question as I'm not asking how to mock/stub extension methods. The question is: is it possible to somehow call its logic without mocking/stubbing it?
I mocked FindAsync by the following code:
var brands = new Mock<DbSet<Brand>>();
ConfigureTheDbSet(brands, brandData);
brands.Setup(b => b.FindAsync(It.IsAny<object[]>())) //substitution of the .SelectAsync(id) method
.Returns<object[]>(ids => brands.Object.FirstOrDefaultAsync(b => b.BrandId == (int) ids[0]));
and it had been working correctly until I added mocking for AsNoTracking to context:
var mockContext = new Mock<ReportDbContext>();
mockContext.Setup(m => m.Set<Brand>()).Returns(brands.Object);
mockContext.Setup(m => m.Set<Brand>().AsNoTracking()).Returns(brands.Object);
And FindAsync returns null. To make it work i added the following mocking:
mockContext.Setup(m => m.Set<Brand>().FindAsync(It.IsAny<object[]>()))
.Returns<object[]>(async d => await brands.Object.FindAsync(d));
Anybody have a clue why this is happening?
IMO, you should be mocking interfaces, for example IBrandRepository. Otherwise whats the point of mocking? - you could just create an instance of your class, call FindAsync() and assert the result as usual..
Here is how I use Moq with interfaces, for example a repo interface;
// arrange
var mockRepo = new Mock<IBrandRepository>();
mockRepo.Setup(o => o.FindAsync(It.IsAny<string>())).ReturnsAsync(new Brand[] { ... });
var someClass = new SomeClass(IBrandRepository); // someClass that use IBrandRepository
// act
string search = "brand1 brand2"; // what the user searches for
var results = someClass.FindBrands(searchText) // internally calls IBrandRepository.FindAsync()
// assert
// Assert.AreEqual(results.Count(), ...
Dimitry, I know that it's been a couple of years. I just had the same issue and this is what I did to get it to work
this.mocContext.Setup(x => x.Company.FindAsync(It.IsAny<string>
())).Returns(Task.FromResult(this.GetCompanyList().SingleOrDefault(x =>
x.CompanyCode.Equals("M5QoKF4AS0"))));
Here mocContext is my Moq'd Database, Company is the table that I want to perform the FindAsync on, the Get CompanyList just pulls from the data the populated the table. Hopefully this helps
I circumvented this mocking by using .Where(entity => entity.PrimaryKey == key).FirstOrDefaultAsync() in place of .FindAsync(key) as FirstOrDefaultAsync did not require a separate mocking and logic is also same between both approaches
For anyone struggling with this, here's another way of doing it:
First: Create a mock of the DbContext and the DbSet, ex:
private static readonly Mock<ApplicationDbContext> mockDbContext = new();
private static readonly Mock<DbSet<Game>> mockGameSet = new();
Second: Setup the Get of the DbSet in the Mocked DbContext, like this:
mockDbContext.SetupGet(_ => _.Games).Returns(mockGameSet.Object);
Third, and Last: Setup the FindAsync() in the mocked DbSet like this:
mockGameSet.Setup(x => x.FindAsync(It.IsAny<int>())).ReturnsAsync(game);
I have a class like below where using Fluent Nhibernate I am getting data from database
public class MyActualClass
{
public MyActualClass(ISessionFactory sessionFactory)
{
this.sessionFactory = sessionFactory;
}
public List<AnnualInformation> GetData()
{
using (session = sessionFactory.OpenSession())
{
var result = session.QueryOver<AnnualInformation>()
.SelectList(list => list
.Select(x => x.Id)
.Select(x => x.CreationDate)
.Select(x => x.AnnualAmount)
.Select(x => x.AnnualCurrency)
.Select(() => monthlyAlias.MonthlyAmount)
.Select(() => monthlyAlias.MonthlyCurrency)
.Select(() => shareAlias.CurrentSharevalue)
.Select(() => miscAlias.MarketValueAmount)
).Where(a => a.Id == 123456).List<AnnualInformation>();
}
}
}
I Have written unit test case for above method like below
public class MyTestClass
{
private static ISessionFactory sessionFactory;
private static ISession session;
public MyTestClass()
{
sessionFactory = A.Fake<ISessionFactory>();
session = A.Fake<ISession>();
A.CallTo(() => sessionFactory.OpenSession()).Returns(session);
}
[Fact]
public void MyTest()
{
var annualDetails =
new AnnualInformation
{
Id= 1,
AnnualCurrency= "string",
AnnualAmount= "Example"
}
var listOfAnnualInformation=
new List<AnnualInformation>
{
annualDetails
};
A.CallTo(session.QueryOver<AnnualInformation>()).WithReturnType<IList<AnnualInformation>>().Returns(listOfAnnualInformation);
var myInstance = new MyActualClass(sessionFactory);
myInstance.GetData();
}
}
Actually if you see below code
session.QueryOver()
.SelectList(...
will return "result" in method GetData(). After that I am manipulating "result" datastructure to get Id, CreationDate, AnnualAmount, AnnualCurrency
Therefore it is very important that some value is returned from "result". My problem is the count of resulty is always 0.
I want the below line of code
A.CallTo(session.QueryOver()).WithReturnType>().Returns(listOfAnnualInformation);
to return a list with atleast one element. Now i believe i clarified my requirements
Please suggest what should be done here ?
Based on the new code (which still doesn't quite compile - missing ;, result isn't returned from GetData, and if it were, the return type of GetData should be IList<AnnualInformation>, but with those changes I was able to get a test to run) I can offer some commentary:
A.CallTo(session.QueryOver<AnnualInformation>()).WithReturnType<IList<AnnualInformation>>()
.Returns(listOfAnnualInformation);
Configures the object that comes back from calling session.QueryOver<AnnualInformation>(). (Note there's no lambda here, so this line actually calls QueryOver.)
session is a Fake, and so when you call QueryOver<AnnualInformation>() on this line, it will return a new Fake IQueryOver. The "WithReturnType…Returns…" configures the new Fake IQueryOver to return listOfAnnualInformation when any method that returns a IList<AnnualInformation> is called.
However, when Fakes' methods are called, unless they've been configured to do something different, they return a new object. So inside GetData when you call QueryOver, you get a different fake IQueryOver, which has not been configured at all. That's one problem.
Second problem: the call to SelectList will return yet another faked IQueryOver.
We can work around all these things:
var aFakeQueryOver = A.Fake<IQueryOver<AnnualInformation, AnnualInformation>>();
A.CallTo(aFakeQueryOver).WithReturnType<IQueryOver<AnnualInformation, AnnualInformation>>()
.Returns(aFakeQueryOver);
A.CallTo(aFakeQueryOver).WithReturnType<IList<AnnualInformation>>()
.Returns(listOfAnnualInformation);
A.CallTo((() => session.QueryOver<AnnualInformation>())).Returns(aFakeQueryOver);
And now the faking behaves as we want. However, all we've done is short-circuit all the logic in GetData, except to see that it uses the sessionFactory to open a session, and then QueryOver on that session. SelectList and Where and List have all been bypassed.
My usual advice in this situation is to make your data access layer as thin as possible and to integration test it. Alternatively, I've seen people suggest having NHibernate use an in-memory MySql database. Still an integration test of sorts, but at least it's more isolated.
I would like to unit test an Add method in a repository that returns void. I'm interested in testing the actual adding of elements without hitting the database (not whether Add was called or not). Is this the correct way?
var list = new List<Foo>();
var repo = new Mock<IFooRepository>();
repo.Setup(x => x.Add(It.IsAny<Foo>()))
.Callback((Foo f) =>
{
list.Add(f);
});
repo.Object.Add(new Foo { FooId = 1 });
Assert.IsTrue(list.Any(x => x.FooId == 1));
No, the only thing you're testing here is Moq itself. You could try mocking the underlying layer, e.g. ISession if you're using Nhibernate.
I have a situation where I am calling an entity and putting in two includes in the ria services call.
public IQueryable<Position> GetPositions(int programID)
{
return _positionRepository.All()
.Where(x => x.ProgramID == programID)
.Include("RecPositions.Person");
}
Id like to get a handle on the Person entity on the front end. I have this working..the code below gives me a handle on the recPositions and in the intellisence I can see the Person object. id like to abstract that entity.
var test = _allRec.Select(x => x.RecPositions).ToList();
test now has my RecPosition...but i want to know how to write a lambda express so i can get a handle on the person object.
I came up with this..does anyone have any objections to this or a better way..
var test = _allRec.SelectMany(x => x.RecPositions)
.Select(p => p.Person)
.ToList();
this seems to give me what I want.