I have been trying to unity test a query that I've created using a repository pattern I cannot seem to figure this one out. It seems that I must be doing something wrong here.
So I've Created a generic repository that may look something like:
public interface IRepository<T> where T:class,IEntity, new()
{
IQueryable<T> Get();
T Get(int id);
T Add(T entity);
T Update(T entity);
void Delete(int id);
}
I also have a Context that may look like:
public class ApplicationContext:DbContext
{
public virtual DbSet<Customer> Customers { get; set; }
public virtual DbSet<User> Users { get; set; }
}
so now I, of course, now have a repository that looks like IRepository<Customer> customersRepository.
In my controller, I have a query that may look like:
var customers = _customerRepository
.Get()
.Include(customer => customer.Users)
.Where(customer=>customer.Status == "active")
.ToList();
So on to my question, I would like to test this but I am getting an error saying
Value cannot be null
my unit test looks like:
[TestMethod]
public void GetCustomerList_ValidParameters_ShouldOnlyReturnItemsWithActiveStatus()
{
//Act
var customers = _customerModel.GetCustomerList(
_parentId, /*parentId*/
string.Empty, /*keywords*/
1, /*page*/
20, /*count*/
out var totalCount, /*totalCount*/
null /*orderBy*/
);
//Assert
Assert.AreEqual(expected:3, actual: customers.Count);
}
my data setup looks like:
private void AddDataToRepository()
{
var customers = new List<Customer>()
{
new Customer{Id = Guid.NewGuid().ToString(), Name = "ABC", Status = "active", Parent_id = _parentId},
new Customer{Id = Guid.NewGuid().ToString(), Name = "DEF", Status = "canceled", Parent_id = _parentId},
new Customer{Id = Guid.NewGuid().ToString(), Name = "HIJ", Status = "active", Parent_id = _parentId},
new Customer{Id = Guid.NewGuid().ToString(), Name = "MNO", Status = "suspended", Parent_id = _parentId},
new Customer{Id = Guid.NewGuid().ToString(), Name = "QRS", Status = "active", Parent_id = _parentId},
};
var users = new List<User>();
var usersMock = new Mock<DbSet<User>>();
_customerRepositoryMock.Setup(x => x.Get().Include(It.IsAny(typeof(User))));
_customerRepositoryMock.Setup(x => x.Get()).Returns(customers.ToDbSet());
}
How can I mock the users here.