Why the below assertion is not working?
Code:
[Test]
public void CreateNewTemplateTest()
{
OnlineSignupModel model = new OnlineSignupModel
{
SalesRepId = 68,
PriceAdvanced = (decimal)22.33,
PriceComplete = (decimal)44.33,
PriceMvr = (decimal)6.33,
SetupFee = (decimal)2.33,
};
Assert.That(model, Has.Exactly(5).Items);
}
Error:
System.ArgumentException : The actual value must be an IEnumerable
Parameter name: actual
at NUnit.Framework.Constraints.ExactCountConstraint.ApplyTo[TActual](TActual actual)
at NUnit.Framework.Assert.That[TActual](TActual actual, IResolveConstraint expression, String message, Object[] args)
at NUnit.Framework.Assert.That[TActual](TActual actual, IResolveConstraint expression)
I am trying to assert that there are 5 properties in the object.
You are asserting incorrectly with the wrong constraint.
There are multiple ways to assert the model, but here is one.
[Test]
public void CreateNewTemplateTest() {
//Arrange
var salesRepId = 68,
var priceAdvanced = (decimal)22.33,
var priceComplete = (decimal)44.33,
var priceMvr = (decimal)6.33,
var setupFee = (decimal)2.33,
//Act
OnlineSignupModel model = new OnlineSignupModel {
SalesRepId = salesRepId,
PriceAdvanced = priceAdvanced,
PriceComplete = priceComplete,
PriceMvr = priceMvr,
SetupFee = setupFee,
};
//Assert
Assert.That(
model.SalesRepId = salesRepId &&
model.PriceAdvanced == priceAdvanced &&
model.PriceComplete == priceComplete &&
model.PriceMvr == priceMvr &&
model.SetupFee == setupFee, Is.True);
}
Consider reviewing the docs on how to use the framework
NUnit Documentation Wiki
Avoiding any commentary on the usefulness of this task, to assert that your model has exactly 5 properties, you can use something like Assert.That(typeof(model).GetProperties().Length == 5);
Related
I'm working on CRUD unit test cases with having configuration .Net 5, Automapper, xUnit etc.
The issue:
So right now I'm having issue specifically in post call and when I uses Dto.
I tried lots of ways to resole it and I was also able to resolve it if I don't use Dto in post call as input parameter and just use Entity it self. (But I don't want to expose entity so I want to make it working with Dto only)
Below is test which is not working and it's controller side implementation.
Failing Test case:
[Fact]
public void PostTest()
{
try
{
//Arrange
var surveyRequest = new SurveyRequest()
{
Id = 0,
Name = "Survey Request 1",
CreateDate = DateTime.Now,
CreatedBy = 1
};
var addedSurveyRequest = new SurveyRequest()
{
Id = 1,
Name = "Survey Request 1",
CreateDate = DateTime.Now,
CreatedBy = 1
};
//setup mock
Mock<IRepositoryWrapper> mockRepo = new Mock<IRepositoryWrapper>();
mockRepo.Setup(m => m.SurveyRequest.Add(addedSurveyRequest)).Returns(new Response<SurveyRequest>(true, addedSurveyRequest));
//auto mapper
var mockMapper = new MapperConfiguration(cfg =>
{
cfg.AddProfile(new AutoMapperProfile());
});
var mapper = mockMapper.CreateMapper();
SurveyRequestController controller = new SurveyRequestController(repositories: mockRepo.Object, mapper: mapper);
//Act
var model = mapper.Map<SurveyRequest, SurveyRequestDto>(source: addedSurveyRequest);
var result = controller.Post(model); // The issue with this post call here is that response remains null on repository level.
//Assert
var okResult = result as OkObjectResult;
Assert.NotNull(okResult);
//we will make sure that returned object is dto and not actual entity
var response = okResult.Value as SurveyRequestDtoWithId;
Assert.NotNull(response);
Assert.Equal(expected: response.Name, actual: model.Name);
}
catch (Exception ex)
{
//Assert
Assert.False(true, ex.Message);
}
}
Controller side post call:
[HttpPost("Insert")]
public IActionResult Post([FromBody] SurveyRequestDto model)
{
try
{
if (!ModelState.IsValid)
return BadRequest(ModelState);
//If I remove this mapping from here, test case will work. (see next working test case)
var entity = _mapper.Map<SurveyRequestDto, SurveyRequest>(source: model);
entity.CreateDate = System.DateTime.Now;
entity.CreatedBy = 1;
var response = _repositories.SurveyRequest.Add(entity: entity); //Response remains null here
_repositories.Save();
if (response.IsSuccess == true)
return new OkObjectResult(_mapper.Map<SurveyRequest, SurveyRequestDtoWithId>(source: response.Data));
else
return new ObjectResult(response.ErrorMessage) { StatusCode = 500 };
}
catch (Exception ex)
{
return new ObjectResult(ex.Message) { StatusCode = 500 };
}
}
Working Test case:
[Fact]
public void PostTest2()
{
try
{
//Arrange
var surveyRequest = new SurveyRequest()
{
Id = 0,
Name = "Survey Request 1",
CreateDate = DateTime.Now,
CreatedBy = 1
};
var addedSurveyRequest = new SurveyRequest()
{
Id = 1,
Name = "Survey Request 1",
CreateDate = DateTime.Now,
CreatedBy = 1
};
//setup mock
Mock<IRepositoryWrapper> mockRepo = new Mock<IRepositoryWrapper>();
mockRepo.Setup(m => m.SurveyRequest.Add(surveyRequest)).Returns(value: new Response<SurveyRequest>(true, addedSurveyRequest));
//auto mapper
var mockMapper = new MapperConfiguration(cfg =>
{
cfg.AddProfile(new AutoMapperProfile());
});
var mapper = mockMapper.CreateMapper();
//setup controlller
SurveyRequestController controller = new SurveyRequestController(repositories: mockRepo.Object, mapper: mapper);
//Act
//var model = mapper.Map<SurveyRequest, SurveyRequestDto>(source: surveyRequest);
var result = controller.Post2(entity: surveyRequest);
//Assert
var okResult = result as OkObjectResult;
Assert.NotNull(okResult);
///we will make sure that returned object is dto and not actual entity
var response = okResult.Value as SurveyRequestDtoWithId;
Assert.NotNull(response);
Assert.Equal(expected: response.Id, actual: addedSurveyRequest.Id);
Assert.Equal(expected: response.Name, actual: addedSurveyRequest.Name);
}
catch (Exception ex)
{
//Assert
Assert.False(true, ex.Message);
}
}
Controller side Post call for working test case:
[HttpPost("Insert")]
public IActionResult Post2([FromBody] SurveyRequest entity)
{
try
{
if (!ModelState.IsValid)
return BadRequest(ModelState);
//var entity = _mapper.Map<SurveyRequestDto, SurveyRequest>(source: model);
//entity.CreateDate = System.DateTime.Now;
//entity.CreatedBy = 1;
var response = _repositories.SurveyRequest.Add(entity: entity); //This returns proper response with saved data and ID
_repositories.Save();
if (response.IsSuccess == true)
return new OkObjectResult(_mapper.Map<SurveyRequest, SurveyRequestDtoWithId>(source: response.Data));
else
return new ObjectResult(response.ErrorMessage) { StatusCode = 500 };
}
catch (Exception ex)
{
return new ObjectResult(ex.Message) { StatusCode = 500 };
}
}
I'm not sure whether my test case setup for mapper is wrong or any other issue. I also tried lots of ways but no luck so far. So posting here if someone can look and help, will be much appreciated.
If you are using IMapper then you can do something like this:
var mapperMock = new Mock<IMapper>();
mapperMock
.Setup(mapper => mapper.Map<SurveyRequestDto, SurveyRequest>(It.IsAny< SurveyRequestDto>()))
.Returns(surveyRequest);
This solution does not utilize the AutoMapperProfile, but because you have only a single mapping that's why I think it not really a problem.
If you want to call Verify on the mapperMock then I would suggest to extract the Map selector delegate like this:
private static Expression<Func<IMapper, SurveyRequestDto>> MapServiceModelFromRequestModelIsAny =>
mapper => mapper.Map<SurveyRequestDto, SurveyRequest>(It.IsAny< SurveyRequestDto>());
Usage
//Arrange
mapperMock
.Setup(MapServiceModelFromRequestModelIsAny)
.Returns(surveyRequest);
...
//Assert
mapperMock
.Verify(MapServiceModelFromRequestModelIsAny, Times.Once);
UPDATE #1
It might also make sense to be as explicit as possible when you make assertion. If you want to you can do deep equality check to make sure that controller's parameter is not amended before the Map call:
private static Expression<Func<IMapper, SurveyRequestDto>> MapServiceModelFromRequestModel(SurveyRequestDto input) =>
mapper => mapper.Map<SurveyRequestDto, SurveyRequest>(It.Is< SurveyRequestDto>(dto => dto.deepEquals(input)));
//Assert
mapperMock
.Verify(MapServiceModelFromRequestModel(model), Times.Once);
This assumes that deepEquals is available as an extension method.
UPDATE #2
As it turned out the mock repository's Setup code also had some problem. Namely it used the surveyRequest rather than a It.IsAny<SurveyRequest>().
Because surveyRequest was specified as the expected parameter that's why the setupped code path is never called but returned with null.
After changed it to It.IsAny then the whole test started to work :D
repoMock
.Setup(repo => repo.SurveyRequest.Add(It.IsAny<SurveyRequest>()))
.Returns(new Response<SurveyRequest>(true, addedSurveyRequest))
My project is using mvc5 in repository pattern and now i've a method in my ScreenManager. Now I've
to write test code for a method which is async type and inside it uses linq query on my repository class. I already wrote a test code(see in bellow) for it but it didn't working. Please help me to get out of this problem.
Error:
Test Failed -
ActionHistoryAsync_WhenCalled_ReturnSceeningActionViewModel Message:
Test method
ScreenMangerTests.ActionHistoryAsync_WhenCalled_ReturnScreenActionViewModel
threw exception: System.InvalidOperationExcetpion: The source
IQueryable doesn't implement.
IDbAsyncEnumerable.Only sources that implement
IDbAsyncEnumerable can be used for Entity Framework asynchronous
operations. For more details see
http://go.microsoft.com/fwlink/?LinkId=287068
I've a repository named
private readonly IScreenActionRepository _iScreenActionRepository;
And I'm Passing it through my constructor.
public ScreenManager(IScreenActionRepository iScreenActionRepository)
{
_iScreenActionRepository= iScreenActionRepository;
}
And finally my Executable method is following
public async Task<IEnumerable<ScreenActionViewModel>> ActionHistoryAsync(long screenId)
{
var result = from a in _iScreenActionRepository.FindAll(s => s.ScreenId == screenId && s.ScreenType == "T")
select new ScreenActionViewModel
{
Id = a.Id,
ScreenId = a.ScreeningId,
ScreeningType = a.ScreenType,
Description = a.Description,
ActionDateTime = a.ActionDateTime,
ActionBy = a.ActionBy,
RoleName = a.RoleName,
};
var z = result.ToList();
return await result.ToListAsync();
}
And my testing code is following
[DataTestMethod]
public async Task ActionHistoryAsync_WhenCalled_ReturnScreenActionViewModel()
{
Mock<IScreenActionRepository> _screenActionRepositoryMock= new Mock<IScreenActionRepository>();
long screenId = 1;
var screenAction = new List<ScreenAction>
{
new ScreenAction
{
ScreenId = 1,
ScreenType = "TP",
Description = "",
ActionDateTime = DateTime.Now,
ActionBy = 3,
RoleName = "Investigator"
}
};
_screenActionRepositoryMock
.Setup(c => c.FindAll(It.IsAny<Expression<Func<ScreenAction, bool>>>()))
.Returns(new Func<Expression<Func<ScreenAction, bool>>, IQueryable<ScreenAction>>(
expr => screenAction.Where(expr.Compile()).AsQueryable()));
//Act
var result = await _manager.ActionHistoryAsync(screenId);
//Assert
Assert.AreEqual(result.First().ActionBy, 3);
Assert.AreEqual(result.First().RoleName, "Investigator");
Assert.AreEqual(result.First().UserFullName, userList.First().FullName);
}
I'm attempting to unit test a relatively simple repository but I've had difficulty figuring out the best approach for dealing with the services and database contexts that the repository requires to be instantiated.
The repository has one public method, which returns a Member object:
public class MemberRepository : IMemberRepository
{
private OServiceContext _openService;
private OpenDbContext _openDbContext;
public MemberRepository(OServiceContext openService, OpenDbContext openDbContext)
{
_openService = openService;
_openDbContext = openDbContext;
}
public async Task<Member> GetMember(int policyMemberId, int policyActivityId)
{
Member member = null;
var members = await _openDbContext.PolicyMembers
.Include(c => c.Contact)
.SingleOrDefaultAsync(x => x.PolicyActivityKey == policyActivityId && x.PolicyMemberKey == policyMemberId);
if (members != null)
{
member = ConvertDataToMember(members);
}
return member;
}}
The ServiceContext collates four distinct services whose purposes are relatively clear from the CTOR:
public OServiceContext(OpenConfiguration config)
{
_username = config.Username;
_password = config.Password;
_authenticationService = new AuthenticationService(config.GetEndpointConfigurationFor(nameof(AuthenticationService)));
_dataService = new DataService(config.GetEndpointConfigurationFor(nameof(DataService)));
_workflowService = new WorkflowService(config.GetEndpointConfigurationFor(nameof(WorkflowService)));
_documentService = new DocumentService(config.GetEndpointConfigurationFor(nameof(DocumentService)));
var viewClasses = AppDomain.CurrentDomain.GetAssemblies()
.SelectMany(x => x.GetTypes())
.Where(x => typeof(IOpenHostView).IsAssignableFrom(x) && !x.IsInterface && !x.IsAbstract && x.IsPublic)
.Select(x => x)
.ToList();
foreach (var c in viewClasses)
{
var attribute = c.GetCustomAttributesData()
.FirstOrDefault(x => x.AttributeType == typeof(OpenViewAttribute));
if (attribute == null)
throw new NullReferenceException($"Unable to find '{nameof(OpenViewAttribute)}' on {nameof(IOpenView)} implementation $'{c.Name}'.");
var viewName = attribute.ConstructorArguments[0].Value.ToString();
var viewConfig = config.GetViewConfigurationFor(viewName);
if (viewConfig == null)
throw new NullReferenceException($"Unable to locate key for Open view '{viewName}'.");
_viewLookup.Add(c, viewConfig.Key);
}
}
The test as it stands:
[Fact]
public void MemberRepository_GetMember_ReturnsValidMember()
{
//Arrange
var mockOServiceConfig = new OpenConfiguration()
{
Username = "test",
Password = "pass",
Remoting = new OpenRemotingConfiguration(),
Endpoints = new List<OpenHEndpointConfiguration>(){
new OpenEndpointConfiguration {
Reference = "test", ServiceUrl = "test", DatabaseKey = 1, EnableMessageLogging = true
} },
Views = new List<OpenViewConfiguration>(),
Entities = new List<OpenEntityConfiguration>()
};
var mockOServiceContext = new Mock<OServiceContext>(mockOServiceConfig);
var mockOpenDbContext = new Mock<OpenDbContext>();
var mockOpenDbSet = new Mock<DbSet<Member>>();
mockOpenDbSet.Setup(s => s.Find(It.IsAny<int>())).Returns(new Member());
mockOpenDbContext.Setup(s => s.Set<Member>()).Returns(mockOpenDbSet.Object);
//Act
var memberRepository = new MemberRepository(mockOServiceContext.Object, mockOpenDbContext.Object);
var member = memberRepository.GetMember(1, 1);
//Assert
Assert.NotNull(member);
Assert.IsAssignableFrom<Member>(member);
}
}
This hits an error -
System.NullReferenceException: 'Object reference not set to an instance of an object.' config was null.
Basically the params aren't valid for the config when sent to the AuthenticationService. But my question isn't really about fixing the error. Is going down the rabbit hole of trying to pass correct mocked params for all these services really the best approach? Surely there's a better way to mock this when all I want to actually test is a relatively trivial Get method?
Also I'm aware that depending on how you approach the mocked services and data, the unit test can mutate into a integration test. I'd just like to hear the thoughts of anyone who has dealt with something similar. This is honestly the first time I've tried to unit test a repository and while I've tried to consume as much as I can on the topic I would genuinely appreciate any guidance.
Have such C# code and try to check method IsFailureProcessStatus to return true.
Query method from dapper class SqlMapper which call stored procedures with parameters.
public class DatabaseManager : IDatabaseManager
{
private readonly SqlConnection CoreDbProcessesConnection;
private readonly SqlConnection HrReportDbConnection;
// there are other private fields with parameters and sql-procedures names
public DatabaseManager(IDbConnectionsProvider dbConnectionsProvider)
{
this.CoreDbProcessesConnection = dbConnectionsProvider.CoreDbProcessesConnection;
this.HrReportDbConnection = dbConnectionsProvider.HrReportDbConnection;
}
public List<CoreProcessStatusDto> GetProcessStatusIds(string ProcessName, DateTime dateTime)
{
var parameters = new DynamicParameters();
parameters.Add(processStatusProcedureParamName01, ProcessName);
parameters.Add(processStatusProcedureParamName02, dateTime);
var output = this.CoreDbProcessesConnection
.Query<CoreProcessStatusDto>(ProcessStatusProcedureName, parameters, commandType: CommandType.StoredProcedure).ToList();
return output;
}
public bool IsFailureProcessStatus(StepDto.StepDescription step, DateTime dateTime)
{
bool isStepFailure = true;
Stopwatch doStepUntil = new Stopwatch();
doStepUntil.Start();
while (doStepUntil.Elapsed < TimeSpan.FromSeconds(step.SecondsElapsed))
{
step.StatusTypesList = this.GetProcessStatusIds(step.ProcessName, dateTime);
var statusTypesStepSelection = step.StatusTypesList.Select(st => st.ProcessStatusTypeId).ToList();
//...
// if...else operations here to make step true or false
//...
}
doStepUntil.Stop();
return isStepFailure;
}
}
Unit test code is located below:
[TestClass]
public class DatabaseManagerTests
{
[TestMethod]
public void IsFailureProcessStatus_ReturnTrue()
{
DateTime dateTime = DateTime.Now;
StepDto step1Dto = new StepDto()
{
JobName = "ETL - HR - FilesImport - Reporting",
JobStepName = "RunMCP_User_Department_Map",
Step = new StepDto.StepDescription()
{
StatusTypesList = new List<CoreProcessStatusDto>(),
ProcessName = "HR_User_Department_Map_Import",
SecondsElapsed = 30,
PackageCount = 2
}
};
using (var mock = AutoMock.GetLoose())
{
var dbProviderMock = new Mock<IDbConnectionsProvider>(MockBehavior.Loose);
var dbMock = new Mock<DatabaseManager>(dbProviderMock.Object);
mock.Mock<IDatabaseManager>()
.Setup(p => p.GetProcessStatusIds(step1Dto.Step.ProcessName, dateTime))
.Returns(GetCoreProcessesStatusIdsTest());
var sut = mock.Provide(dbMock.Object);
//var sut = mock.Create<DatabaseManager>();
var actual = sut.IsFailureProcessStatus(step1Dto.Step, dateTime);
Assert.IsTrue(actual);
}
}
private List<CoreProcessStatusDto> GetCoreProcessesStatusIdsTest()
{
var output = new List<CoreProcessStatusDto>()
{
new CoreProcessStatusDto() { ProcessStatusTypeId = 3 },
new CoreProcessStatusDto() { ProcessStatusTypeId = 2 }
};
return output;
}
}
I tried to setup GetProcessStatusIds method to return values when calling sut.IsFailureProcessStatus code, but while debug its run GetProcessStatusIds and throw NullReferenceException exception when try calling Query method.
Test Name: IsFailureProcessStatus_ReturnTrue
Test Outcome: Failed
Result StackTrace:
at Dapper.SqlMapper.<QueryImpl>d__140`1.MoveNext() in C:\projects\dapper\Dapper\SqlMapper.cs:line 1066
at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
at Dapper.SqlMapper.Query[T](IDbConnection cnn, String sql, Object param, IDbTransaction transaction, Boolean buffered, Nullable`1 commandTimeout, Nullable`1 commandType) in C:\projects\dapper\Dapper\SqlMapper.cs:line 721
at ATP.HR.FolderWatcher.Service.Managers.DatabaseManager.GetProcessStatusIds(String ProcessName, DateTime dateTime) in C:\HOME\anatolii.dmitryv\src\HRM\hr-folder-watcher-service\ATP.HR.FolderWatcher.Service\Managers\DatabaseManager.cs:line 46
at ATP.HR.FolderWatcher.Service.Managers.DatabaseManager.IsFailureProcessStatus(StepDescription step, DateTime dateTime) in C:\HOME\anatolii.dmitryv\src\HRM\hr-folder-watcher-service\ATP.HR.FolderWatcher.Service\Managers\DatabaseManager.cs:line 83
at ATP.HR.FolderWatcher.Service.Test.DatabaseManagerTests.IsFailureProcessStatus_ReturnTrue() in C:\HOME\anatolii.dmitryv\src\HRM\hr-folder-watcher-service\ATP.HR.FolderWatcher.Service.Tests\DatabaseManagerTests.cs:line 57
Result Message:
Test method ATP.HR.FolderWatcher.Service.Test.DatabaseManagerTests.IsFailureProcessStatus_ReturnTrue threw exception:
System.NullReferenceException: Object reference not set to an instance of an object.
And what exactly I do wrong in mock of this method? How I can say to test do not run this GetProcessStatusIds and just return hardcoded values?
tried this using but it didnt work for me:
using (var mock = AutoMock.GetLoose())
{
mock.Mock<IDatabaseManager>()
.Setup(p => p.GetProcessStatusIds(It.IsAny<string>(), It.IsAny<DateTime>()))
.Returns(GetCoreProcessesStatusIdsTest());
var sut = mock.Create<DatabaseManager>();
var actual = sut.IsFailureProcessStatus(step1Dto.Step, dateTime);
Assert.IsTrue(actual);
}
The first thing when doing unit testing is to define the goal of the test, in your question you are trying to test the inside logic of IsFailureProcessStatus, the problem here is that you mocking the interface IDatabaseManager that has the IsFailureProcessStatus method.
You don't need that mocking, you will only will need to mock IDatabaseManager when it uses as supplier for other clients services.
And because you are testing the inside logic of IsFailureProcessStatus you will only need to mock and setup method that are needed for the execution of the inside logic like IDbConnectionsProvider and setup its method of CoreDbProcessesConnection for it to be available to the DatabaseManager real instance.
var dbProviderMock = new Mock<IDbConnectionsProvider>(MockBehavior.Loose);
dbProviderMock
.Setup(p => p.CoreDbProcessesConnection)
.Returns(new SqlConnection(...));
DatabaseManager databaseManager = new DatabaseManager(dbProviderMock.Object);
var actual = databaseManager.IsFailureProcessStatus(step1Dto.Step, dateTime);
Assert.IsTrue(actual);
I can understand why you wrongly tried to mock GetProcessStatusIds, but it won't needed since we have the real instance of DatabaseManager, so you will only be mocking depended interfaces that are needed in the execution process of GetProcessStatusIds, thats why we does not need here the setup of HrReportDbConnection.
I have the following code
public bool IsUnitAvailable()
{
this.isUnitAvailable = false;
if(isUnitAvailable == false)
{
var exception = new Exception("Unit Unavailable");
exception.Data.Add("Quotation","1234567");
exception.Data.Add("propertyDate", "2016-10-10"); this.GetElmahExtensionWrapper().LogToElmah(exception);
}
}
return this.isUnitAvailable;
}
and the following unit test.
[TestMethod]
public void WhenUnitIsNotAvailableExceptionShouldBeLoggedInElmahTest()
{
//Arrange
var iPricingServiceMock = new Mock<IPricingService>(MockBehavior.Strict);
iPricingServiceMock.Setup(
counter => counter.IsUnitAvailableOn(It.IsAny<Unit>(),It.IsAny<DateTime>())).Returns(false);
var mockElmahExtensionWrapper = TestHelper.mk.GetMock<IElmahExtensionWrapper>();
// act
var quotation = new Quotation();
quotation.SetElmahExtensionWrapper(mockElmahExtensionWrapper.Object);
quotation.IsUnitAvailable();
//assert
mockElmahExtensionWrapper.Verify(counter => counter.LogToElmah(It.IsAny<Exception>()), Times.Exactly(1));
//change the test to verify that the exception that was logged had 2 Data properties?
}
The unit test is working. How can I change the test to verify that the exception that was logged had 2 Data properties? Changing the code to the following throws a "Cannot resolve symbol Data property" error.
mockElmahExtensionWrapper.Verify
(
counter => counter.LogToElmah
(
It.IsAny<Exception>(ex=>ex.Data.Count == 2)
),
Times.Exactly(1)
);
Change the verification to something like:
mockElmahExtensionWrapper.Verify(counter => counter.LogToElmah(It.Is<TraceException>(ex => ex.Data["Quotation"] == "1234567" && ex.Data["propertyDate"] == "2016-10-10"), Times.Exactly(1));