How to test Add method with Moq in C# - c#

I try write a unit test for Add method from repository class. I'm using EF6 and Moq. My test method looking that:
public static Mock<DbSet<T>> CreateDbSetMock<T>(IEnumerable<T> elements) where T : class
{
var elementsAsQueryable = elements.AsQueryable();
var dbSetMock = new Mock<DbSet<T>>();
dbSetMock.As<IQueryable<T>>().Setup(m => m.Provider).Returns(elementsAsQueryable.Provider);
dbSetMock.As<IQueryable<T>>().Setup(m => m.Expression).Returns(elementsAsQueryable.Expression);
dbSetMock.As<IQueryable<T>>().Setup(m => m.ElementType).Returns(elementsAsQueryable.ElementType);
dbSetMock.As<IQueryable<T>>().Setup(m => m.GetEnumerator()).Returns(elementsAsQueryable.GetEnumerator());
return dbSetMock;
}
[Test()]
public void AddTest()
{
// Arrange
Mock<DbSet<Tytul>> titlesMock = CreateDbSetMock(new List<Tytul>());
Mock<OzinDbContext> titlesContextMock = new Mock<OzinDbContext>();
titlesContextMock.Setup(x => x.Tytuly).Returns(titlesMock.Object);
titlesMock.Setup(x => x.Add(It.IsAny<Tytul>())).Returns((Tytul t) => t);
IRepository<Tytul> tytulRepository = TytulRepository(titlesContextMock.Object);
Tytul tytul = new Tytul
{
Identyfikator = "ABC"
};
// Act
tytulRepository.Add(tytul);
// in Add method:
//dbContext.Tytuly.Add(entity);
//dbContext.SaveChanges();
Tytul tytulInDb = tytulRepository.GetDetail(t => t.Identyfikator == "ABC");
// in GetDetail method:
//return dbContext.Tytuly.FirstOrDefault(predicate);
// Assert
Assert.AreEqual(tytulInDb.Identyfikator, tytul.Identyfikator);
}
My problem is GetDetail method returns null, but I expected the tytulInDb object. What is wrong? How write thist test correct?

Extract the fake data source for the DbSet into a local variable so it can be interacted with later in the test setup. Add a Callback to the Add setup to add the passed argument to the data source so that there is actual data to be acted upon by the mock when invoked.
// Arrange
var data = new List<Tytul>(); //<<< local variable
Mock<DbSet<Tytul>> titlesMock = CreateDbSetMock(data);
var titlesContextMock = new Mock<OzinDbContext>();
titlesContextMock.Setup(x => x.Tytuly).Returns(titlesMock.Object);
titlesMock
.Setup(x => x.Add(It.IsAny<Tytul>()))
.Returns((Tytul t) => t)
.Callback((Tytul t) => data.Add(t)); //<<< for when mocked Add is called.
IRepository<Tytul> tytulRepository = TytulRepository(titlesContextMock.Object);
//...Code removed for brevity
Also when setting up the DbSet Mock use a delegate for the Returns to allow for multiple enumerations as returning just the value will only allow for one pass of the forward only enumerator.
dbSetMock.As<IQueryable<T>>()
.Setup(m => m.GetEnumerator())
.Returns(() => elementsAsQueryable.GetEnumerator()); //<<< note delegate

Related

Setup with ReturnsAsync, need to return passed in value but getting null

I need to mock my IVehicleRecordsRepository for some tests. So here's the repo interface:
public interface IVehicleRecordsRepository
{
Task<VehicleRecord> StoreAsync(VehicleRecord veh, Guid? userId = null);
//...
}
and now I try to mock it in the xUnit test so StoreMethod() should return the same value that was passed in as a parameter. Here's the test that tests this scenario:
[Fact]
public async Task ShouldGetValueFromMockedMethod()
{
var mockRepo = new Mock<IVehicleRecordsRepository>();
mockRepo
.Setup(repo => repo.StoreAsync(It.IsAny<VehicleRecord>(), Guid.NewGuid()))
.ReturnsAsync((VehicleRecord veh, Guid userId) => veh)
// tried this too -> .Returns((VehicleRecord veh, Guid userId) => Task.FromResult(veh))
;
VehicleRecord vr = new VehicleRecord(newVehicle, Guid.NewGuid());
var testVeh = await mockRepo.Object.StoreAsync(vr);
Assert.NotNull(testVeh); // ====> FAILS HERE
Assert.AreEqual(vr, testVeh);
}
So, how can I get the same value I passed into StoreAsync() in return ?
Moq version: 4.7.99.0
I've not used Moq, so forgive my ignorance.
In your act statement:
var testVeh = await mockRepo.Object.StoreAsync(vr);
you're only passing in the Vehicle Record ('vr'), but your mocked object is set up to also expect a Guid.NewGuid(), correct?
mockRepo.Setup(repo => repo.StoreAsync(It.IsAny<VehicleRecord>(), Guid.NewGuid()))
Could it be that it's not matching the expectation and therefore, never calls the "(mockObject.)ReturnsAsync" method?
Have you tried doing something like:
var guid = Guid.NewGuid;
VehicleRecord vr = new VehicleRecord(newVehicle, guid);
var testVeh = await mockRepo.Object.StoreAsync(vr, guid);
Or, perhaps simplifying it a bit, change your mockObject to not expect a Guid, since you're passing in only the VehicleRecord:
mockRepo.Setup(repo => repo.StoreAsync(It.IsAny<VehicleRecord>()))

Setup a mocked EF Service method

I have the following method in my NewsDataService class
public IEnumerable<NewsModel> GetImportantNews()
{
var result = this.newsfeedRepository.GetAll(
x => x.IsImportant == true,
x => new NewsModel()
{
Creator = x.User.UserName,
AvatarPictureUrl = x.User.AvatarPictureUrl,
Content = x.Content,
CreatedOn = x.CreatedOn
})
.OrderByDescending(x => x.CreatedOn);
return result;
}
My question is...
How do I setup the mocked service method (GetImportantNews),
so that it returns a list of NewsModel which are "Important"?
My idea is something like this, but it is not working so far, because it is always returning the full list.
var expectedResult = new List<Newsfeed>()
{
new Newsfeed()
{
IsImportant = false,
},
new Newsfeed()
{
IsImportant = true
}
};
mockedNewsfeedRepository
.Setup(x => x.GetAll(
It.IsAny<Expression<Func<Newsfeed, bool>>>(),
It.IsAny<Expression<Func<Newsfeed, NewsModel>>>()
)).Returns(expectedResult);
Basically what I want is my "expectedResult" to be filtered by the logic in the method.
You have access to the invocation arguments when returning a value. Apply the predicate and projection expression arguments to the fake data source using linq like in the example below.
mockedNewsfeedRepository
.Setup(x => x.GetAll(
It.IsAny<Expression<Func<Newsfeed, bool>>>(),
It.IsAny<Expression<Func<Newsfeed, NewsModel>>>()
))
// access invocation arguments when returning a value
.Returns((Expression<Func<Newsfeed, bool>> predicate, Expression<Func<Newsfeed, NewsModel>> projection) =>
expectedResult.Where(predicate.Compile()).Select(projection.Compile())
);
Source: Moq Quickstart

Mock Linq `Any` predicate with Moq

I'm trying to mock AnyAsync method in my repository with below codes but repository always returns false.
The signature of AnyAsync is:
Task<bool> AnyAsync<TEntity>(Expression<Func<TEntiry, bool>> predicate)
I tried the following setups:
1:
mockCustomerRepository.Setup(r => r.AnyAsync(c => c.Email == "some#one.com"))
.ReturnsAsync(true);
2:
Expression<Func<CustomerEntity, bool>> predicate = expr =>
expr.CustomerPerson.Email == "some#one.com";
mockCustomerRepository.Setup(r => r.AnyAsync(It.Is<Expression<Func<CustomerEntity, bool>>>
(criteria => criteria == predicate))).ReturnsAsync(true);
3:
mockCustomerRepository.Setup(r => r.AnyAsync(It.IsAny<Expression<Func<CustomerEntity, bool>>>()))
.ReturnsAsync(true);
My test:
public class Test
{
Mock<ICustomerRepository> mockCustomerRepository;
public Test()
{
mockCustomerRepository = new Mock<ICustomerRepository>();
}
[Fact]
public async Task CustomerTest()
{
var customer = ObjectFactory.CreateCustomer(email: "some#one.com");
var sut = new CustomerService(mockCustomerRepository.Object);
var result = await sut.ValidateCustomerAsync(customer);
.
.
.
}
}
My CustomerService.ValidateCustomerAsync method:
public async Task<OperationResult> ValidateCustomerAsync(CustomerEntity customer)
{
var errors = new List<ValidationResult>();
if (await _repository.AnyAsync(c => c.Email == customer.Email))
errors.Add(new ValidationResult("blah blah")));
I've also read this but it doesn't work too.
The following snippet shows the correct way to mock your AnyAsync method:
[TestMethod]
public async Task TestMethod1()
{
var fakeCustomerRepo = new Mock<ICustomerRepository>();
var foo = false;
fakeCustomerRepo.Setup(repository => repository.AnyAsync(It.IsAny<Expression<Func<CustomerEntity, bool>>>()))
.Callback<Expression<Func<CustomerEntity, bool>>>(
expression =>
{
var func = expression.Compile();
foo = func(new CustomerEntity() {Email = "foo#gmail.com"});
})
.Returns(() => Task.FromResult(foo));
var customer = new CustomerEntity() {Email = "foo#gmail.com"};
var result = await fakeCustomerRepo.Object.AnyAsync<CustomerEntity>(c => c.Email == customer.Email);
Assert.IsTrue(result);
customer = new CustomerEntity() { Email = "boo#gmail.com" };
result = await fakeCustomerRepo.Object.AnyAsync<CustomerEntity>(c => c.Email == customer.Email);
Assert.IsFalse(result);
}
using the above setup you can verify your predicate which is part of your unit behavior.
I think you're running into the difficulties of matching predicates. Funcs or expressions of Funcs use reference-equality, so just using == to compare the two instances isn't going to work. (As a general rule, if you can't get predicate1.Equals(predicate2) to return true, Moq's argument matchers aren't going to match.)
This is a little unorthodox, but I refer you to my answer to a similar question for FakeItEasy matchers, which in turn points you at a number of techniques for validating predicates.
All I can see that should cause this problem are two options:
1. The repository method does not come from an interface that you should mock to return the desired value, as it is not marked with virtual.
2. The types (TEntity) you use in method do not match when you are using the moq.
AnyAsync<TEntity>(Expression<Func<TEntity, bool>>
as you can setup for let's say MemberEntity and call the ValidateCustomerAsync with a CustomerEntity.
Maybe I am wrong but, but as far as I have read for methods that return only a Task, .Returns(Task.FromResult(default(object))) can and should be used.
So in your case it would be mocksCustomerRepository.Setup(r => r.AnyAsync(c => c.Email == "some#one.com")).Returns(Task.FromResult(true));

C# Moq Entity Framework 6 Data Context Add Operation

I want to test that a method adds a record to a DBSet under a certain condition:
public static void AddTriggeredInternalTransactions(IDataContext dc, ExternalTransaction transaction)
{
if (transaction [meets condition A])
dc.InternalTransactions.CreateInverseTransaction(transaction);
// do other stuff under other conditions
}
private static void CreateInverseTransaction(this IDbSet<InternalTransaction> transactions, ExternalTransaction from)
{
var internalTransaction = transactions.Create();
from.CopyToInternalTransaction(internalTransaction);
transactions.Add(internalTransaction);
}
Now, I already have tests for CopyToInternalTransaction(). I just need to call AddTriggeredInternalTransactions() and verify that [condition A] results in the new record being added).
I started with http://msdn.microsoft.com/en-us/data/dn314429.aspx, then used other Google and StackOverflow searches. Before tackling my "real" test, I'm trying to do a simple test just to verify whether a record has been added to a dataset, but I'm stuck on this. Can anyone point out my flaw(s)?
var internals = new Mock<DbSet<InternalTransaction>>();
var theData = new List<InternalTransaction>().AsQueryable();
internals.As<IQueryable<InternalTransaction>>().Setup(m => m.Provider).Returns(theData.Provider);
internals.As<IQueryable<InternalTransaction>>().Setup(m => m.Expression).Returns(theData.Expression);
internals.As<IQueryable<InternalTransaction>>().Setup(m => m.ElementType).Returns(theData.ElementType);
internals.As<IQueryable<InternalTransaction>>().Setup(m => m.GetEnumerator()).Returns(theData.GetEnumerator());
var mockDC = new Mock<IDataContext>();
mockDC.Setup(q => q.InternalTransactions).Returns(internals.Object);
mockDC.Setup(q => q.InternalTransactions.Create()).Returns(new InternalTransaction());
mockDC.Setup(q => q.InternalTransactions.Add(It.IsAny<InternalTransaction>()));
var it = mockDC.Object.InternalTransactions.Create();
it.Id = "123";
mockDC.Object.InternalTransactions.Add(it);
internals.Verify(e => e.Add(It.Is<InternalTransaction>(d => d.Id == "123")), Times.Once());
//or: Assert.Equal(1, mockDC.Object.InternalTransactions.Count());
This test fails with: Expected invocation on the mock once, but was 0 times: e => e.Add(It.Is(d => d.Id == "123")) No setups configured. No invocations performed.
The Assert statement, if used instead, fails with a NotImplementedException: "The member IQueryable.Provider has not been implemented on type DbSet~1Proxy_1 which inherits from DbSet1. Test doubles for DbSet1 must provide implementations of methods and properties that are used."
After comments by Adam and Stuart plus further experimentation, I was able to reduce my test case to the following working test case:
var internals = new Mock<DbSet<InternalTransaction>>();
var mockDC = new Mock<IDataContext>();
mockDC.Setup(q => q.InternalTransactions).Returns(internals.Object);
internals.Setup(q => q.Create()).Returns(new InternalTransaction());
var transaction = new ExternalTransaction { [set criteria for Condition A] };
SomeBusinessObject.AddTriggeredInternalTransactions(mockDC.Object, transaction);
// verify the Add method was executed exactly once
internals.Verify(e => e.Add(It.IsAny<InternalTransaction>()), Times.Once());

Moq Verify that Method was called with any expression

I'm new to Moq and I'm trying to Mock my repository.
The method I'm Writing a unit test for is calling the repository like this:
var paymentState = _agreementPaymentStateRepository.SingleOrDefault(
s => s.Agreement.ID == agreementID);
I'm trying to set up my moq like this:
_agreementPaymentStateRepositoryMock
.Setup(m => m.SingleOrDefault(s => s.AgreementID == 1))
.Returns(AgreementPayMentStateMocks.GetOne);
I pass my mocked repository to the class but the paymentState variable is null after the call is made. (I would gladely skip specifying the expression as well).
Any help is much appreciated.
public PaymentState GetPaymentState(int agreementID)
{
try
{
_log.AgreementPaymentStateServiceGetStateStart(agreementID);
var paymentState =
_agreementPaymentStateRepository.SingleOrDefault(s => s.Agreement.ID == agreementID);
var stateToGet = MapStateToGet(paymentState);
_log.AgreementPaymentStateServiceGetStateReturn(agreementID, paymentState.LatestStatus);
return stateToGet;
}
catch (Exception ex)
{
_log.ServiceException(ex.ToString());
throw;
}
}
and the test:
var paymentState = AgreementPayMentStateMocks.GetPayMentState();
_agreementPaymentStateRepositoryMock.Setup(m => m.SingleOrDefault(s => s.AgreementID == 1)).Returns(AgreementPayMentStateMocks.GetOne);
var service = new AgreementPaymentStateService(_agreementPaymentStateRepositoryMock.Object, _log.Object);
var result = service.GetPaymentState(1);
_agreementPaymentStateRepositoryMock.Verify(m => m.Match(aps => aps.SingleOrDefault(s => s.AgreementID == 1)), Times.Exactly(1));
Instead of having a concrete predicate in the SingleOrDefault call, use Moq's It.IsAny<T> method:
_agreementPaymentStateRepositoryMock
.Setup(m => m.SingleOrDefault(It.IsAny<Expression<Func<bool,PaymentState>>>()))
.Returns(AgreementPayMentStateMocks.GetOne);

Categories