Unit Tests on Method that uses GetEntitiesAync (DocumentDB) - linq

After mocking DocumentDBRepository class with its GetEntitiesAsync() method in the unit test, it is return a null value which is not I expect it to return.
Here's my method that I need to test
public async Task<Books> GetBooksByBookIdAsyncByLinq(string bookId)
{
var books = await _individualRepository.GetEntitiesAsync(t => t.BookID == bookId);
if (individualResponse.Any())
{
return individualResponse.FirstOrDefault();
}
return null;
}
Here's the unit test of this method, noticed that I set up the GetEntitiesAsync() method and expect it to return a book value. But it is returning null when I ran it:
[Fact]
public void Test_GetBooksByBookIdAsyncByLinq()
{
//Arrange
var bookID = "000";
//Mock DocumentDBRepository
var mockDocumentDBRepository = new Mock<IRepository<Book>>();
var expected = Get_BookValue();
mockDocumentDBRepository.Setup(x => x.GetEntitiesAsync(x => x.BookID == bookID))
.Returns(Task.FromResult(expected));
var component = new BookComponent(mockDocumentDBRepository.Object);
//Act
var result = component.GetBooksByBookIdAsyncByLinq(bookID);
//Assert
result.Result.Should().NotBeNull().And.
BeOfType<Book>();
}
private Book Get_BookValue(){
IEnumerable<Book> result = new List<Book>
{ new Book
{ BookID = "000", BookName = "TestSourceSystemName" } };
return result;
}
When I ran the unit test and debug inside the GetBooksByBookIdAsyncByLinq() method, it is not getting any results from the books variable and return null without any error.
The interesting thing is, when I change the GetEntitiesAsync() method to RunSQLQueryAsync() method, which means using SQL query instead of Linq, the unit test is returning the correct result.
Here's the method I am testing:
public async Task<Books> GetBooksByBookIdAsyncBySQL(string bookId)
{
var books = await _individualRepository.RunSQLQueryAsync("select * from c where c.BookID ==" + bookId);
if (individualResponse.Any())
{
return individualResponse.FirstOrDefault();
}
return null;
}
And here's the unit test for this method, noticed that I set up the RunQueryAsync() method and expect to return a book value. And it works:
[Fact]
public void Test_GetBooksByBookIdAsyncBySQL()
{
//Arrange
var bookID = "000";
var sqlQuery = "select * from c where c.BookID ==" + bookId;
//Mock DocumentDBRepository
var mockDocumentDBRepository = new Mock<IRepository<Book>>();
var expected = Get_BookValue();
//mockDocumentDBRepository.Setup(x => x.GetEntitiesAsync(x => x.BookID == bookID))
// .Returns(Task.FromResult(expected));
mockDocumentDBRepository.Setup(x => x.RunQueryAsync(sqlQuery))
.Returns(Task.FromResult(expected));
var component = new BookComponent(mockDocumentDBRepository.Object);
//Act
var result = component.GetBooksByBookIdAsyncBySQL(bookID);
//Assert
result.Result.Should().NotBeNull().And.
BeOfType<Book>();
}
private Book Get_BookValue(){
IEnumerable<Book> result = new List<Book>
{ new Book
{ BookID = "000", BookName = "TestSourceSystemName" } };
return result;
}
So I am thinking maybe the way I mock GetEntitiesAsync() method is incorrect. But I am not sure why...
Here are the RunQueryAsync() and GetEntitiesAsync() methods for reference:
public async Task<IEnumerable<T>> GetEntitiesAsync(Expression<Func<T, bool>> predicate)
{
IDocumentQuery<T> query = GetQueryByPredicate(predicate);
List<T> results = new List<T>();
while (query.HasMoreResults)
{
results.AddRange(await query.ExecuteNextAsync<T>());
}
return results;
}
public async Task<IEnumerable<T>> RunQueryAsync(string queryString)
{
IDocumentQuery<T> query = GetQueryBySQL(queryString);
List<T> results = new List<T>();
while (query.HasMoreResults)
{
results.AddRange(await query.ExecuteNextAsync<T>());
}
return results;
}

The Setup method tries to look at the arguments passed into your method, and only match the specified behavior if those arguments are the same.
When you use GetQueryBySQL, Moq is able to detect that the sqlQuery string is the same (as in object.Equals()) as what's passed in, so it works correctly.
When you use GetEntitiesAsync, Moq looks at the two Expressions and thinks they are different because Expression comparison is based on memory equality. So even though the two x => x.BookID == bookIDs look the same to you and me, they are different Expressions at runtime.
Try using It.IsAny<>() instead:
mockDocumentDBRepository
.Setup(x => x.GetEntitiesAsync(It.IsAny<Expression<Func<Book, bool>>()))
.Returns(Task.FromResult(expected));
Supposing you get that working, you can use Callback or other strategies to test that the expression passed into GetEntitiesAsync has the behavior you're expecting it to have.

Related

Spring unit tests [webflux, cloud]

I am new to the topic of unit testing and my question is whether I should perform the test as such of each line of code of a method or in what ways I can perform these tests to have a good coverage, if also, should exceptions be evaluated or not?
If for example I have this service method that also uses some helpers that communicate with other microservices, someone could give me examples of how to perform, thank you very much.
public Mono<BankAccountDto> save(BankAccountDto bankAccount) {
var count = findAccountsByCustomerId(bankAccount.getCustomerId()).count();
var customerDto = webClientCustomer
.findCustomerById(bankAccount.getCustomerId());
var accountType = bankAccount.getAccountType();
return customerDto
.zipWith(count)
.flatMap(tuple -> {
final CustomerDto custDto = tuple.getT1();
final long sizeAccounts = tuple.getT2();
final var customerType = custDto.getCustomerType();
if (webClientCustomer.isCustomerAuthorized(customerType, accountType, sizeAccounts)) {
return saveBankAccountAndRole(bankAccount);
}
return Mono.error(new Exception("....."));
});
}
EDIT
public Mono<BankAccountDto> save(BankAccountDto bankAccount) {
var count = findAccountsByCustomerId(bankAccount.getCustomerId()).count();
var customerDto = webClientCustomer
.findCustomerById(bankAccount.getCustomerId());
return customerDto
.zipWith(count)
.flatMap(tuple -> {
final var customDto = tuple.getT1();
final var sizeAccounts = tuple.getT2();
final var accountType = bankAccount.getAccountType();
// EDITED
return webClientCustomer.isCustomerAuthorized(customDto, accountType, sizeAccounts)
.flatMap(isAuthorized -> {
if (Boolean.TRUE.equals(isAuthorized)) {
return saveBankAccountAndRole(bankAccount);
}
return Mono.error(new Exception("No tiene permisos para registrar una cuenta bancaria"));
});
});
}
Given that you want to unit test this code, you would need to mock dependencies such as webClientCustomer.
Then you should always test whatever are the relevant paths within the code. Looking at your code I only see three relevant ones to be tested:
the method returns an empty Mono if webClientCustomer.findCustomerById(bankAccount.getCustomerId()); returns an empty Mono;
saveBankAccountAndRole(bankAccount) is called and your save() method actually returns whatever saveBankAccountAndRole(bankAccount) returns. This would should happen if webClientCustomer.isCustomerAuthorized(customerType, accountType, sizeAccounts) is true;
the method returns an exception if webClientCustomer.isCustomerAuthorized(customerType, accountType, sizeAccounts) is false.

Mock IDocumentQuery with ability to use query expressions

I need to be able to mock IDocumentQuery, to be able to test piece of code, that queries document collection and might use predicate to filter them:
IQueryable<T> documentQuery = client
.CreateDocumentQuery<T>(collectionUri, options);
if (predicate != null)
{
documentQuery = documentQuery.Where(predicate);
}
var list = documentQuery.AsDocumentQuery();
var documents = new List<T>();
while (list.HasMoreResults)
{
documents.AddRange(await list.ExecuteNextAsync<T>());
}
I've used answer from https://stackoverflow.com/a/49911733/212121 to write following method:
public static IDocumentClient Create<T>(params T[] collectionDocuments)
{
var query = Substitute.For<IFakeDocumentQuery<T>>();
var provider = Substitute.For<IQueryProvider>();
provider
.CreateQuery<T>(Arg.Any<Expression>())
.Returns(x => query);
query.Provider.Returns(provider);
query.ElementType.Returns(collectionDocuments.AsQueryable().ElementType);
query.Expression.Returns(collectionDocuments.AsQueryable().Expression);
query.GetEnumerator().Returns(collectionDocuments.AsQueryable().GetEnumerator());
query.ExecuteNextAsync<T>().Returns(x => new FeedResponse<T>(collectionDocuments));
query.HasMoreResults.Returns(true, false);
var client = Substitute.For<IDocumentClient>();
client
.CreateDocumentQuery<T>(Arg.Any<Uri>(), Arg.Any<FeedOptions>())
.Returns(query);
return client;
}
Which works fine as long as there's no filtering using IQueryable.Where.
My question:
Is there any way to capture predicate, that was used to create documentQuery and apply that predicate on collectionDocuments parameter?
Access the expression from the query provider so that it will be passed on to the backing collection to apply the desired filter.
Review the following
public static IDocumentClient Create<T>(params T[] collectionDocuments) {
var query = Substitute.For<IFakeDocumentQuery<T>>();
var queryable = collectionDocuments.AsQueryable();
var provider = Substitute.For<IQueryProvider>();
provider.CreateQuery<T>(Arg.Any<Expression>())
.Returns(x => {
var expression = x.Arg<Expression>();
if (expression != null) {
queryable = queryable.Provider.CreateQuery<T>(expression);
}
return query;
});
query.Provider.Returns(_ => provider);
query.ElementType.Returns(_ => queryable.ElementType);
query.Expression.Returns(_ => queryable.Expression);
query.GetEnumerator().Returns(_ => queryable.GetEnumerator());
query.ExecuteNextAsync<T>().Returns(x => new FeedResponse<T>(query));
query.HasMoreResults.Returns(true, true, false);
var client = Substitute.For<IDocumentClient>();
client
.CreateDocumentQuery<T>(Arg.Any<Uri>(), Arg.Any<FeedOptions>())
.Returns(query);
return client;
}
The important part is where the expression passed to the query is used to create another query on the backing data source (the array).
Using the following example subject under test for demonstration purposes.
public class SubjectUnderTest {
private readonly IDocumentClient client;
public SubjectUnderTest(IDocumentClient client) {
this.client = client;
}
public async Task<List<T>> Query<T>(Expression<Func<T, bool>> predicate = null) {
FeedOptions options = null; //for dummy purposes only
Uri collectionUri = null; //for dummy purposes only
IQueryable<T> documentQuery = client.CreateDocumentQuery<T>(collectionUri, options);
if (predicate != null) {
documentQuery = documentQuery.Where(predicate);
}
var list = documentQuery.AsDocumentQuery();
var documents = new List<T>();
while (list.HasMoreResults) {
documents.AddRange(await list.ExecuteNextAsync<T>());
}
return documents;
}
}
The following sample tests when an expression is passed to the query
[TestMethod]
public async Task Should_Filter_DocumentQuery() {
//Arrange
var dataSource = Enumerable.Range(0, 3)
.Select(_ => new Document() { Key = _ }).ToArray();
var client = Create(dataSource);
var subject = new SubjectUnderTest(client);
Expression<Func<Document, bool>> predicate = _ => _.Key == 1;
var expected = dataSource.Where(predicate.Compile());
//Act
var actual = await subject.Query<Document>(predicate);
//Assert
actual.Should().BeEquivalentTo(expected);
}
public class Document {
public int Key { get; set; }
}

Testing stack exchange redis method using stubs

I have a method like below.
public async Task<bool> AddAsync<T>(IList<Tuple<string, T>> items) where T : class
{
RedisKey[] redisKeys = new RedisKey[items.Count];
RedisValue[] redisValues = new RedisValue[items.Count];
var sb = await this.redisCachingHelperPriv.CreateLuaScriptForMset(redisKeys, redisValues, items, this.customKey);
var redisResult = await this.connectionMultiplexerPriv.GetDatabase().ScriptEvaluateAsync(sb, redisKeys, redisValues);
return redisResult.ToString() == "OK";
}
I am trying to write test method for above method using stubs like below.
public void AddAsync_List_Functionality_TestMethod()
{
bool returnTask = false;
using (ShimsContext.Create())
{
IDatabase idata = new StubIDatabase
{ScriptEvaluateAsyncStringRedisKeyArrayRedisValueArrayCommandFlags = (A, B, C, D) =>
{
//Need to return RedisResult object. But not able to create it.
}
};
ShimConnectionMultiplexer.AllInstances.GetDatabaseInt32Object = (A, B, C) => { return idata; };
List<Tuple<string, string>> cacheItems = new List<Tuple<string, string>>();
cacheItems.Add(Tuple.Create("test", "test"));
this.redisCachingObj = new RedisCaching(this.redisCachingConfigObj, this.redisCachingHelperObj);
this.redisCachingObj.InitializeAsync();
Task task = this.redisCachingObj.AddAsync(cacheItems);
task.Wait();
Assert.IsTrue(task.IsCompleted);
}
}
Inside stub for ScriptEvaluateAsync I need to return a task containing RedisResult object. But I am not able to create RedisResult object as it is an abstract class.
Could anyone please help me out in this?

Need Help Writing Unit Test that on Method that requires HttpContext.Current.User

I am trying to write some unit tests for my MVC3 project (the first tests for this project) and I am getting stumped. Basically, I have a MemberQueries class that is used by my MemberController to handle all the logic.
I want to start writing tests on this class and want to start with a simple example. I have a method in this class called IsEditModeAvailable which determines if the user is a member of the "Site Administrator" role or that the user is able to edit their own data, but no one elses. I determine the last requirement by comparing the passed in Id value to the HttpContext User property.
The problem that I'm running into is I don't know how to mock or inject the proper parameters into my unit tests when creating the MemberQueries object. I am using, NUnit, Moq and Ninject, but I'm just not sure how to write the code. If I'm just not structuring this properly, please let me know as I'm a complete noob to unit testing.
Here's a sample of the code from my MemberQueries class:
public class MemberQueries : IMemberQueries
{
private readonly IRepository<Member> _memberRepository;
private readonly IMemberServices _memberServices;
private readonly IPrincipal _currentUser;
public MemberQueries(IUnitOfWork unitOfWork, IMemberServices memberServices, IPrincipal currentUser)
{
_memberRepository = unitOfWork.RepositoryFor<Member>();
_memberServices = memberServices;
_currentUser = currentUser;
}
public bool IsEditModeAvailable(int memberIdToEdit)
{
if (_currentUser.IsInRole("Site Administrator")) return true;
if (MemberIsLoggedInUser(memberIdToEdit)) return true;
return false;
}
public bool MemberIsLoggedInUser(int memberIdToEdit)
{
var loggedInUser = _memberServices.FindByEmail(_currentUser.Identity.Name);
if (loggedInUser != null && loggedInUser.Id == memberIdToEdit) return true;
return false;
}
}
Here's a sample from my MemberServices class (which is in my domain project, referenced by MemberQueries):
public class MemberServices : IMemberServices
{
private readonly IRepository<Member> _memberRepository;
public MemberServices(IUnitOfWork unitOfWork)
{
_memberRepository = unitOfWork.RepositoryFor<Member>();
}
public Member Find(int id)
{
return _memberRepository.FindById(id);
}
public Member FindByEmail(string email)
{
return _memberRepository.Find(m => m.Email == email).SingleOrDefault();
}
}
Finally, here's the stub of the unit test I am trying to write:
[Test]
public void LoggedInUserCanEditTheirOwnInformation()
{
var unitOfWork = new UnitOfWork();
var currentUser = new Mock<IPrincipal>();
// I need to somehow tell Moq that the logged in user has a HttpContext.User.Name of "jdoe#acme.com"
var memberServices = new Mock<MemberServices>();
// I then need to tell Moq that it's FindByEmail("jdoe#acme.com") method should return a member with a UserId of 1
var memberQueries = new MemberQueries(unitOfWork, memberServices.Object, currentUser.Object);
// If the logged in user is "jdoe#acme.com" who has an Id of 1, then IsEditModeAvailable(1) should return true
Assert.IsTrue(memberQueries.IsEditModeAvailable(1));
}
It looks like you are trying to test the MemberQueries.IsEditModeAvailable method. You have 2 cases to cover here. The Site Administrators case and the case where there's a currently logged user whose id matches the one passed as argument. And since the MemberQueries class relies purely on interfaces you could mock everything:
[TestMethod]
public void EditMode_Must_Be_Available_For_Site_Administrators()
{
// arrange
var unitOfWork = new Mock<IUnitOfWork>();
var currentUser = new Mock<IPrincipal>();
currentUser.Setup(x => x.IsInRole("Site Administrator")).Returns(true);
var memberServices = new Mock<IMemberServices>();
var memberQueries = new MemberQueries(unitOfWork.Object, memberServices.Object, currentUser.Object);
// act
var actual = memberQueries.IsEditModeAvailable(1);
// assert
Assert.IsTrue(actual);
}
[TestMethod]
public void EditMode_Must_Be_Available_For_Logged_In_Users_If_His_Id_Matches()
{
// arrange
var unitOfWork = new Mock<IUnitOfWork>();
var currentUser = new Mock<IPrincipal>();
var identity = new Mock<IIdentity>();
identity.Setup(x => x.Name).Returns("john.doe#gmail.com");
currentUser.Setup(x => x.Identity).Returns(identity.Object);
currentUser.Setup(x => x.IsInRole("Site Administrator")).Returns(false);
var memberServices = new Mock<IMemberServices>();
var member = new Member
{
Id = 1
};
memberServices.Setup(x => x.FindByEmail("john.doe#gmail.com")).Returns(member);
var memberQueries = new MemberQueries(unitOfWork.Object, memberServices.Object, currentUser.Object);
// act
var actual = memberQueries.IsEditModeAvailable(1);
// assert
Assert.IsTrue(actual);
}
Actually there's a third case you need to cover: you have a currently logged in user, who is not a Site Administrator and whose id doesn't match the one passed as argument:
[TestMethod]
public void EditMode_Should_Not_Be_Available_For_Logged_In_Users_If_His_Id_Doesnt_Match()
{
// arrange
var unitOfWork = new Mock<IUnitOfWork>();
var currentUser = new Mock<IPrincipal>();
var identity = new Mock<IIdentity>();
identity.Setup(x => x.Name).Returns("john.doe#gmail.com");
currentUser.Setup(x => x.Identity).Returns(identity.Object);
currentUser.Setup(x => x.IsInRole("Site Administrator")).Returns(false);
var memberServices = new Mock<IMemberServices>();
var member = new Member
{
Id = 2
};
memberServices.Setup(x => x.FindByEmail("john.doe#gmail.com")).Returns(member);
var memberQueries = new MemberQueries(unitOfWork.Object, memberServices.Object, currentUser.Object);
// act
var actual = memberQueries.IsEditModeAvailable(1);
// assert
Assert.IsFalse(actual);
}
The good news is that you are passing the user as an IPrincipal into the code that needs it rather than referring to HttpContext.Current.User. All you should need to do is setup the mock IPrincipal so that it returns the vales you need for that test.
var mockIdentity = new Mock<IIdentity>();
mockIdentity.Setup(x => x.Name).Returns("joe#acme.com");
var mockPrincipal = new Mock<IPrincipal>();
mockPrincipal.Setup(x => x.Identity).Returns(mockIdentity.Object);

Unit test with Moq

I am using Moq for unit testing, and I am trying to write my first unit test. My layers are "Controller=>Service=>Repository".
(I am using unity and repository pattern.)
Whenever I run my unit test, the actual value is always 0 like _service.GetEquipStates().Count() = 0. I do not know where I am doing wrong. Please suggest.
My unit test code is the following one:
private ITestService _service;
private Mock<ITestRepository> RepositoryMoc;
[TestInitialize]
public void Initialize() {
RepositoryMoc= new Mock<ITestRepository>();
_service = new TestService(RepositoryMoc.Object)
}
[TestMethod]
public void GetEquipmentState() {
var stateList = new[] { new State { ID = 1, Desc= "test" } };
RepositoryMoc.Setup(es => es.GetStates(true)).Returns(stateList );
Assert.AreEqual(1, _service.GetStates().Count());
}
Your setup is done for the methode GetState with prameter true.
RepositoryMoc.Setup(es => es.GetStates(true)).Returns(stateList);
But your call in the Assert-Statement is for a method GetState without a parameter. Is the method GetState declared with a default parameter or do you have to functions (one with a bool parameter and one without)?
Just make your call in the assert-statement like this and it should work.
Assert.AreEqual(1, _service.GetStates(true).Count());
I have replicated your code in one of my solutions, and the test passes fine.
private Mock<IAccessor> RepositoryMoc;
private Controller _service;
[TestMethod]
public void TestMethod()
{
// Arrange
_service = new Controller();
RepositoryMoc = new Mock<IAccessor>();
_service.Accessor = RepositoryMoc.Object;
var stateList = new[] { new State { ID = 1, Desc = "test" } };
RepositoryMoc.Setup(es => es.GetStates(true)).Returns(stateList);
// Act & Assert
Assert.AreEqual(1, _service.GetStates().Count());
}
Is the code exactly as is in your solution ?

Resources