c#


Moq C# MongoDB FindAsync return value


Recently we implemented a generic version of a repository for Mongo.
Repository
public async Task<IList<T>> FindAsync<T>(FilterDefinition<T> t) where T : IMongoModel
{
var collection = _connection.GetCollection<T>();
var result = await collection.FindAsync<T>(t);
return await result.ToListAsync();
}
public async Task<IList<T>> FindAsync<T>(Expression<Func<T, bool>> filter) where T : IMongoModel
{
var collection = _connection.GetCollection<T>();
var result = await collection.FindAsync(filter);
return await result.ToListAsync();
}
Code Being Called
private async Task<MongoDb.Advertisement.Service.Models.AdvertisementFiles.Advertisement> DealerZipCodeAndLocation(MongoDb.Advertisement.Service.Models.AdvertisementFiles.Advertisement advertisement, string searchPhone)
{
var matchingDealers = await _mongoRepository.FindAsync(Builders<Dealer>.Filter.ElemMatch(y => y.Phones, z => z.PhoneNumber == searchPhone));
if (!matchingDealers.Any())
{
return advertisement;
}
if (matchingDealers.Count > 1)
{
_logger.Warning("More than one dealer found with {PhoneNumber}", searchPhone);
}
var matchingDealer = matchingDealers.FirstOrDefault();
if (matchingDealer.Geocode == null)
{
var geoCode = await _geoLocationCache.GetGeocodByZipCode(matchingDealer.Address.ZipCode);
if (geoCode.status != "OK")
{
return advertisement;
}
advertisement.Geocode = geoCode;
advertisement.ZipCode = matchingDealer.Address.ZipCode;
await UpdateGeocode<Dealer>(matchingDealer.Id, geoCode);
}
return advertisement;
}
Have also tried following signatures
var matchingDealers = await _mongoRepository.FindAsync<Dealer>(x => x.Phones.Any(y => y.PhoneNumber == searchPhone));
var matchingDealers = await _mongoRepository.FindAsync(filter);
When mocking out the FindAsync call, I am having difficulty with the return. The issue is either with the signature not matching, or more likely with async.
Moq Setup
I have tried both versions (also with It.IsAny<string>() in place of the phone number)
_testFixture.MongoRepository.Setup(x => x.FindAsync(Builders<Dealer>.Filter.ElemMatch(y => y.Phones, z => z.PhoneNumber == _testFixture.GetAdvertisementWithNoZipCode().OriginalPhoneNumber))).Returns(Task.FromResult(_testFixture.GetDealerWithZipCode()));
_testFixture.MongoRepository.Setup(x => x.FindAsync(Builders<Dealer>.Filter.ElemMatch(y => y.Phones, z => z.PhoneNumber == _testFixture.GetAdvertisementWithNoZipCode().OriginalPhoneNumber))).ReturnsAsync(_testFixture.GetDealerWithZipCode());
Return Objects Tried
public IList<Dealer> GetDealerWithZipCode()
{
return new List<Dealer>
{
new Dealer
{
Active = true,
DealerName = "City Chevrolet",
Phones = new List<Phone>
{
new Phone
{
PhoneNumber = "4033809999"
}
},
MasterCode = "CHEV01",
RevisionDate = DateTime.UtcNow
}
};
}
public async Task<IList<Dealer>> GetDealerWithZipCode()
{
return await Task.Run(() => new List<Dealer>
{
new Dealer
{
Active = true,
DealerName = "City Chevrolet",
Phones = new List<Phone>
{
new Phone
{
PhoneNumber = "4033809999"
}
},
MasterCode = "CHEV01",
RevisionDate = DateTime.UtcNow
}
});
}
Exception
System.ArgumentNullException: Value cannot be null.
Parameter name: source
at System.Linq.Enumerable.Any[TSource](IEnumerable`1 source)
at Domain.Advertisement.Service.BackgroundProcessors.ZipCodeAndLocationProcessor.<DealerZipCodeAndLocation>d__5.MoveNext() in C:\Repos\Vader\AdSvc\domain\domain.advertisement.service\BackgroundProcessors\ZipCodeAndLocationProcessor.cs:line 60
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
at Domain.Advertisement.Service.BackgroundProcessors.ZipCodeAndLocationProcessor.<ProcessVehicleAdvertisementLocation>d__4.MoveNext() in C:\Repos\Vader\AdSvc\domain\domain.advertisement.service\BackgroundProcessors\ZipCodeAndLocationProcessor.cs:line 42
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
at Domain.Advertisement.Service.Tests.Processors.ZipCodeAndLocation.ZipCodeAndLocationProcessorFacts.<ProcessVehicleAdvertisementLocation_AdLineHasEmptyZipCodePhoneMatchesDealer_GeocodeIsAddedToAdvertisement>d__3.MoveNext() in C:\Repos\Vader\AdSvc\tests\domain.advertisement.service.tests\Processors\ZipCodeAndLocation\ZipCodeAndLocationProcessorFacts.cs:line 47
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Xunit.Sdk.TestInvoker`1.<>c__DisplayClass48_1.<<InvokeTestMethodAsync>b__1>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Xunit.Sdk.ExecutionTimer.<AggregateAsync>d__4.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Xunit.Sdk.ExceptionAggregator.<RunAsync>d__9.MoveNext()
When I debug I am getting an ArgumentNullException because I am not getting my return object. I know I have an issue in my setup, but I am struggling to figure out where.
Given the method under test which I assume is DealerZipCodeAndLocation you should be able to setup the repository mock as follows
_testFixture.MongoRepository
.Setup(_ => _.FindAsync(It.IsAny<FilterDefinition<Dealer>>()))
.ReturnsAsync(_testFixture.GetDealerWithZipCode());
this should simplify the expectations for the test assuming
Task<IList<T>> FindAsync<T>(FilterDefinition<T> t) where T : IMongoModel
belongs to the repository interface provided by _testFixture.MongoRepository, and should safely exercise the method under test to the line
if (matchingDealer.Geocode == null) {
//...
Where you would also need to make sure that the other dependencies like the logger and geo location cache are properly mocked for the test to be exercised as expected.

Related Links

How to deal with multiple resource files for localization?
HtmlHelper extension with script
crystal reports how to align logo?
An object reference is required for the non-static field, method, or property error on new EventHandler
WPF: two controls binding to one source, how to filter the binding?
JQuery set value to custom made server control
C# Network Stream still contains old data after read
How to check when an exe application ends? [closed]
Regex to find multiple matched items at one time
Get instance of containing class
Data binding linq query to datagridView in Entity Framework 5.0
Opening a URL in the default browser in a Windows 8 desktop application
ASP.NET C# Missing Expression Error during Oracle insert
Dynamic URL MVC [closed]
Programmatically get pending changes for a specific folder in a specific project?
Const Vs. Enum for Method Parameter

Categories

HOME
postgresql
gcc
stata
system-calls
network-programming
oracle-sqldeveloper
postgresql-9.3
mysqli
terminal
mediarecorder
angularjs-directive
powerquery
opacity
zabbix
markdown
pip
vsixmanifest
promotions
soap-client
rename
theory
decoding
tmux
swift3.1
brightway
owncloud
geography
jq
bug-reporting
ajaxcontroltoolkit
fibonacci
smali
ballerinalang
smart-device
tftp
ipython-parallel
concrete5
deferred
tikz
jcr
oracle-nosql
rtos
imageprocessor
console.readline
susy
uitextview
text-extraction
f#-fake
scrapinghub
ack
android-doze-and-standby
jks
jcs
trusted-computing
indoor-positioning-system
dimensionality-reduction
boost-range
networkstream
jigsaw
bytearray
angularfire
supervised-learning
laterjs
boost-propertytree
pebble-js
paypal-subscriptions
gnu-sort
javapackager
sparkcore
pdcurses
log-analysis
vectordrawable
grails-3.0.9
mri
backtrace
fedena
register-allocation
react-os
javacompiler
image-preloader
carrier
pechkin
cab
static-class
mandelbrot
proj4
coinbase-php
ftpwebrequest
string-length
microsoft-speech-platform
event-propagation
reflexil
virtual-printer
pex-and-moles
flexbuilder
nbehave
s60
activescaffold
hp-trim
pixel-bender
retrospectiva
opengl-to-opengles
qlibrary
software-update

Resources

Mobile Apps Dev
Database Users
javascript
java
csharp
php
android
MS Developer
developer works
python
ios
c
html
jquery
RDBMS discuss
Cloud Virtualization
Database Dev&Adm
javascript
java
csharp
php
python
android
jquery
ruby
ios
html
Mobile App
Mobile App
Mobile App