callback is not called using moq + autofaq - c#

I have a unit test done using moq to mock the objects, and the test is working fine, and now I want to use autofac +moq, but I'm having a few problems.
this is the test:
using (var mock = AutoMock.GetLoose())
{
var issues = new List<Issue>();
issues.Add(new Issue { Organization = "org", Repository = "repo", Number = 1 });
issues.Add(new Issue { Organization = "org", Repository = "repo", Number = 2 });
var numKeys = 0;
mock.MockRepository.Create<IStorageService>()
.Setup(myMock => myMock.GetBatchIssues(It.IsAny<string>(),
It.IsAny<string>(),
It.IsAny<IList<string>>()))
.Callback((string org, string repo, IList<string> keys) => numKeys = keys.Count)
.Returns(issues);
var sut = mock.Create<IssueReceiveService>();
var check = await sut.CheckInStorage("org", "repo", issues);
Assert.AreEqual(issues.Count, numKeys);
}
the call to sut.CheckInStorage return null, and the variable numKeys is not updated to the correct value. This test works fine using just moxk, so I suppose I'm missing something how to configure a mock with autoMock.
Where can I find more informations?
UPDATE:
after a few more tests I found the solution
using (var mock = AutoMock.GetLoose())
{
var issues = new List<Issue>();
issues.Add(new Issue { Organization = "org", Repository = "repo", Number = 1 });
issues.Add(new Issue { Organization = "org", Repository = "repo", Number = 2 });
var numKeys = 0;
mock.Mock<IStorageService>()
.Setup(myMock => myMock.GetBatchIssues(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<IList<string>>()))
.Callback((string org, string repo, IList<string> keys) => numKeys = keys.Count)
.Returns(issues);
var sut = mock.Create<IssueReceiveService>();
var check = await sut.CheckInStorage("org", "repo", issues);
Assert.AreEqual(issues.Count, numKeys);
}

after a few more tests I found the solution
using (var mock = AutoMock.GetLoose())
{
var issues = new List<Issue>();
issues.Add(new Issue { Organization = "org", Repository = "repo", Number = 1 });
issues.Add(new Issue { Organization = "org", Repository = "repo", Number = 2 });
var numKeys = 0;
mock.Mock<IStorageService>()
.Setup(myMock => myMock.GetBatchIssues(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<IList<string>>()))
.Callback((string org, string repo, IList<string> keys) => numKeys = keys.Count)
.Returns(issues);
var sut = mock.Create<IssueReceiveService>();
var check = await sut.CheckInStorage("org", "repo", issues);
Assert.AreEqual(issues.Count, numKeys);
}

Related

Assert.AreSame is not working for okObject result even when the objects are same

I have the following code for a Unit test.I'm using Mock library for unit testing.
Even when the objects are the same, the assert call fails.
var service = new Mock<IRiskAssetProxyService>();
var controller = new AssetProxyController(service.Object);
List<AssetProxyWrapper> mockAssetProxyMappings = new List<AssetProxyWrapper>();
AssetProxyWrapper awrapper1 = new AssetProxyWrapper
{
assetProxyMapping = new AssetProxyMapping
{
AssetId = "testasset",
IsActive = true,
ProxyAssetId = "testproxy",
AssetIdType = "testtype",
testcode= "testcode",
ProxyAssetIdType = "testproxytype"
},
myCodes = new List<string> { "test"}
};
mockAssetProxyMappings.Add(awrapper1);
OkObjectResult okResult = new OkObjectResult(mockAssetProxyMappings);
service.Setup(service => service.GetAllAssetProxyMapping()).Returns(mockAssetProxyMappings);
var result = controller.GetAll() ;
Assert.AreSame(okResult, result);
What i'm i doing wrong? Please advice.

Unit testing a query to a CRM database with Nunit

I have the following method that I am trying to write unit tests for:
public Entity GetContactByEmail(string email)
{
var queryExpression = new QueryExpression(CRMFieldNames.Contact.EntityName);
queryExpression.ColumnSet = new ColumnSet(CRMFieldNames.Contact.EmailAddress1);
queryExpression.Criteria.AddCondition(CRMFieldNames.Contact.EmailAddress1, ConditionOperator.Equal, email);
var entities = _crmExecutor.Execute(service => service.RetrieveMultiple(queryExpression));
if (entities.Entities.Count > 0)
{
return entities.Entities[0];
}
return entities.Entities.FirstOrDefault();
}
I have attempted the following unit test:
[Test]
public void GetContactByEmail_AnyCase_ReturnsEntity()
{
var email = "lorem#ipsum.com";
var repository = CreateEmailSendRepository();
var query = new QueryExpression("contact");
var entityCollection = new EntityCollection();
entityCollection.Entities.Add(new Entity());
_crmExecutor.Execute(_organizationService => _organizationService.RetrieveMultiple(query)).Returns(entityCollection);
var result = repository.GetContactByEmail(email);
Assert.IsInstanceOf<Entity>(result);
}
private EmailSendRepository CreateEmailSendRepository()
=> new EmailSendRepository(_crmExecutor);
It is failing on the conditional in the GetContactByEmail method saying that entities = null. Can someone please point me in the right direction of giving entities a value here?

Mock.Verify() failed - This setup was not matched?

I have the following test code.
var test = "Test";
var command = new MyCommand { V = test };
var mock = new Mock<IRepository>(); // IRepository has the method of Save()
var p = new P(test);
mock.Setup(x => x.Save(p)).Verifiable();
var sut = new C(mock.Object);
var result = await sut.M(command);
mock.Verify();
The test should pass. However, it failed with the error of,
Message:
Moq.MockException : Mock:
This mock failed verification due to the following:
IRepository x => x.Save(P):
This setup was not matched.
Stack Trace:
Mock.Verify()
sut.M() will convert a string X to type P with value of P(X).
It seems to me that you want to verify that the Save method from your mock is called with a specific value, and not just a type.
I have tried something like the following and believe it should work. I have modified your example.
var test = "Test";
var command = new MyCommand { V = test };
var mock = new Mock<IRepository>(); // IRepository has the method of Save()
var p = new P(test);
mock.Setup(x => x.Save(It.IsAny<P>());
var sut = new C(mock.Object);
var result = await sut.M(command);
mock.Verify(x => x.Save(It.Is<P>(v => v.Value.Equals(p.Value))), Times.AtLeastOnce);
This tests that the values of the specific property are equal.
I Tested this with the following test:
var test = "Test";
var mock = new Mock<ITestRepository>(); // ITestRepository has the method of Save()
var p = new P(test);
mock.Setup(x => x.Save(It.IsAny<P>()));
mock.Object.Save(new P(test));
mock.Verify(x => x.Save(It.Is<P>(v => v.Value.Equals(p.Value))), Times.AtLeastOnce);

Using mock to unit test my API having reference to multiple respositories

I have a API implemented using ABPZero framework using EFcore. I have done integration test using sqlite in memory db as per the suggestions on documentation. But I am puzzled when trying to do unit test on the same API using mock[assuming that mock is faster in terms of execution]
I have referece to different repositoreis on that method. Should I be mocking the service or the repository on the testcase?
public PagedResultDto<PatientSearchDTO> Search(PatientInpu
PatientInput)
{
List<PatientSearchDTO> patientSearch = new
List<PatientSearchDTO>();
int totalCount=0;
try
{
var filterText = PatientInput.Filter.Trim().ToLower();
//Get the patients filtered usinng the filter text.
var result = this._demoRepository.GetAll().Where(x =>
x.Dem_Firstname.ToLower().Contains(filterText)
);
var treatment = _treatmentRepository.GetAll();
// Get the treatments for the pateints we fetched.
var demotreatment = (from tdemo in result
join treat in treatment on tdemo.Dem_Acu_Id equals treat.trm_acu_id into g1
from treat in g1.DefaultIfEmpty()
select new
{
Acu_Id = tdemo.Dem_Acu_Id,
FirstName = tdemo.Dem_Firstname.Trim(),
Surname = tdemo.Dem_Surname.ToUpper().Trim() + (string.IsNullOrWhiteSpace(tdemo.Dem_Alias) ? string.Empty : " (" + tdemo.Dem_Alias.Trim() + ")"),
MaidenName = tdemo.Dem_Maidname.Trim(),
DOB = tdemo == null ? DateTime.MinValue : tdemo.Dem_Dob,
RegistrationNumber = tdemo.Dem_RegNo == null ? string.Empty : tdemo.Dem_RegNo.Trim(),
Photo = tdemo.Dem_Photo,
TreatmentStartDate = treat == null ? Convert.ToDateTime("1900-01-01 00:00:00.000") : Convert.ToDateTime(treat.trm_tr_startdate)
});
This is the constructor of the test,
public PatientServiceTests()
{
service = LocalIocManager.Resolve < IPatientService >();
//creating set up data.
SetUp();
}
private void SetUp()
{
//Arrange
UsingIdeasDbContext(context =>
{
context.Demos.Add(new TDemo
{
Id = 1,
Dem_Acu_Id = "1",
Dem_Firstname = "Jack",
Dem_Surname = "Jill",
Dem_Maidname = "",
Dem_Dob = DateTime.UtcNow.AddYears(-30),
Dem_Alias = "JJ",
Dem_RegNo = "123456"
});
context.TTreatment.Add(new TTreatment
{
trm_acu_id = "1",
trm_cycle = "4207-1",
trm_tr_startdate = DateTime.UtcNow.AddMonths(-1),
});
}
[Fact]
public void Should_SearchPatients()
{
PatientInpu input = new PatientInpu () { Filter = "ja",
Sorting = "FirstName ASC", SkipCount = 0, MaxResultCount = 10 };
var result = service.Search(input);
result.Items.Count.ShouldBe(1);
}
What will be the best way to unit test this method? in -memory or Mock?
Ideally you should have an abstraction layer over the database implementation. Your caller doesn't need to know the implementation details.
Having said that, expose the DB functionality via an interface and while unit testing, mock out the interface/service (use can use mocking frameworks like Moq or write a custom mock).

Unit Testing xUnit Asserting 2 Collections with Moq Interface

Good day everyone,
I'm new in xunit and even in unit testing. I have a code here and I'm trying to assert two collection of list. But I have no idea how to assert and pass this test. Here's my code
[Theory]
[InlineData(1)]
public void GetAllStudents_Exempt1(int number)
{
// arrange
var studentRepo = new Mock<IStudentRepository>();
var listOfStudents = new List<Student> { new Student { StudentId = 1, Firstname = "Firstname1", Lastname = "Firstname1" },
new Student{StudentId=2, Firstname="Firstname2",Lastname="Lastname2"} };
var getAllStudentDetailsExempt1 = studentRepo.Setup(s => s.GetStudents()).Returns(listOfStudents.Where(x => x.StudentId != number));
var studentService = new StudentService(studentRepo.Object);
// act
var getStudentsDetails = studentService.ListOfStudentsExempt1(1);
// assert
// I don't have any idea how to assert
}
First a few notes:
var getAllStudentDetailsExempt1 = studentRepo
.Setup(s => s.GetStudents())
.Returns(listOfStudents.Where(x => x.StudentId != number));
you don't need var getAllStudentDetailsExempt1, you can just setup your repo-mock...
studentRepo
.Setup(s => s.GetStudents())
.Returns(listOfStudents.Where(x => x.StudentId != number));
You probably want to change:
// act
var getStudentsDetails = studentService.ListOfStudentsExempt1(1);
to use the number variable...
// act
var getStudentsDetails = studentService.ListOfStudentsExempt1(number);
So then you can assert by checking some properties:
Assert.Equals(1, getStudentsDetails.Count);
Assert.Equals("FirstName1", getStudentsDetails.First().Firstname);
etc. etc.
Give it a shot!

Categories

Resources