I am using Moq 4.18.1. I have to setup a mock for the following method signature:
Task AddMultiMessagesWithTransactionAsync<T>(List<(string queueName, T content, string messageId)> messageInfos, bool createQueue = false) where T : class;
The special thing is the generic type inside the tupel, which is at the first parameter. And I think there lies the problem. Other mock-setups in the same project are working fine. The mock looks like:
Mock<IServiceBusService> sbSrvMock2 = new();
var messageInfos = It.IsAny<List<(string queueName, It.IsAnyType content, string messageId)>>();
var createQueue = It.IsAny<bool>();
sbSrvMock2
.Setup(sb => sb.AddMultiMessagesWithTransactionAsync<It.IsAnyType>(messageInfos, createQueue))
.Callback(new InvocationAction((inv) =>
{
var p1 = inv.Arguments[0];
var p2 = inv.Arguments[1];
Console.WriteLine("I was here");
}));
The callback is never triggered! Do I have a problem with setting up the signature? Is it something with async?
I am new on Dart, I want to map a list of objects to only get the attribute firstName, but I am getting that error:
Error: The getter 'firstName' isn't defined for the class 'Map<String, String>'.
- 'Map' is from 'dart:core'.
void main() {
var employes = [
{"firstName":"John", "lastName":"Doe"},
{"firstName":"Anna", "lastName":"Smith"},
{"firstName":"Peter", "lastName":"Jones"}
];
var mapFirstName = employes.map((detail) { return {"firstName": detail.firstName}});
print(mapFirstName);
}
How I can fix it?
In Dart, you have to use bracket notation instead of the dot notation to access the values of the keys in the map.
Your code should look like:
var mapFirstName = employes.map((detail) => {"firstName": detail["firstName"]});
In an ASP.NET Core application I have a profile class (for AutoMapper) like this:
public class CandidateProfile : AutoMapper.Profile
{
public CandidateProfile()
{
CreateMap<Job.Candidate, Job.Candidate>()
.ForMember(x => x.Id, y => y.UseDestinationValue());
}
}
In Startup.cs I registerAutoMapper with DI like this:
services.AddAutoMapper(c =>
{
c.AddProfile<JobProfile>();
c.AddProfile<CandidateProfile>();
c.AddProfile<ApplicationProfile>();
}
My aim is to not change the value of the Id property in the destination object. However the destination Id always gets set to 0 which is the value of the source object.
existingCandidate = _mapper.Map(app.Candidate, existingCandidate);
After calling this code, existingCandidate.Id is 0.
What am I doing wrong?
My aim is to not change the value of the Id property in the
destination object.
So, basically for Id, you don't want the source property to be mapped to the destination property. You want it left alone. Simply Ignore the mapping for that property then -
CreateMap<Candidate, Candidate>()
.ForMember(x => x.Id, y => y.Ignore());
Edit :
Following is the code that is working for me with above configuration (version 10.0) -
public void Test()
{
Candidate appCandidate = new Candidate { Id = 0, Name = "alice" };
Candidate existingCandidate = new Candidate { Id = 4, Name = "bob" };
existingCandidate = _Mapper.Map(appCandidate, existingCandidate);
}
I am currently building an angular website and using Web Api 2 as my data service.
I have encountered a issue with populating child entities when i call a http get method. The child entities (fields) does not appear in the Json response.
//Fetch records by page size
public ICollection<CompanyStatDomainModel> GetRecordsByPageSize(int page)
{
const int pgeSize = 20;
var result = _companyStatRepo.AllIncluding(c => c.CompanyDomainModel, c => c.RatingDomainModels)
.OrderBy(c => c.CompanyStatId).Skip(page * pgeSize).Take(pgeSize).ToList();
return result;
}
CONTROLLER
public ICollection<CompanyStatDomainModel> GetRecordsByPageSize(int page)
{
var companyStatService = new CompanyStatService();
return companyStatService.GetRecordsByPageSize(page);
}
WebApiConfig.cs
var json = config.Formatters.JsonFormatter;
json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects;
config.Formatters.Remove(config.Formatters.XmlFormatter);
The easiest way to solve this kind of problem is by manually projecting the results of the EF query to the desired structure, something like
var result = _companyStatRepo
.AllIncluding(c => c.CompanyDomainModel, c => c.RatingDomainModels)
.OrderBy(c => c.CompanyStatId).Skip(page * pgeSize)
.Take(pgeSize).Select(csr => new CompanyStatRepo {
prop1 = csr.prop1,
prop2 = csr.prop2,
...
RatingDomainModels = csr.RatingDomainModels.ToList()
}).ToList();
I don't know the real structure of your classes, but this is the basic idea.
I'm trying to verify a method call using Moq, but I can't quite get the syntax right. Currently, I've got this as my verify:
repository.Verify(x => x.ExecuteNonQuery("fav_AddFavorites", new
{
fid = 123,
inputStr = "000456"
}), Times.Once());
The code compiles, but the test fails with the error:
Expected invocation on the mock once, but was 0 times:
x => x.ExecuteNonQuery("fav_AddFavorites", new <>f__AnonymousType0<Int32, String>(123, "000456"))
No setups configured.
Performed invocations:
IRepository.ExecuteNonQuery("fav_AddFavorites", { fid = 123, inputStr = 000456 })
How can I verify the method call and match the method parameters for an anonymous type?
UPDATE
To answer the questions:
I am trying to verify both that the method was called and that the parameters are correct.
The signature of the method I'm trying to verify is:
int ExecuteNonQuery(string query, object param = null);
The setup code is simply:
repository = new Mock<IRepository>();
UPDATE 2
It looks like this is a problem with Moq and how it handles anonymous types in .Net. The code posted by Paul Matovich runs fine, however, once the code and the test are in different assemblies the test fails.
This Passes
public class Class1
{
private Class2 _Class2;
public Class1(Class2 class2)
{
_Class2 = class2;
}
public void DoSomething(string s)
{
_Class2.ExecuteNonQuery(s, new { fid = 123, inputStr = "000456" });
}
}
public class Class2
{
public virtual void ExecuteNonQuery(string s, object o)
{
}
}
/// <summary>
///A test for ExecuteNonQuery
///</summary>
[TestMethod()]
public void ExecuteNonQueryTest()
{
string testString = "Hello";
var Class2Stub = new Mock<Class2>();
Class1 target = new Class1(Class2Stub.Object);
target.DoSomething(testString);
Class2Stub.Verify(x => x.ExecuteNonQuery(testString, It.Is<object>(o => o.Equals(new { fid = 123, inputStr = "000456" }))), Times.Once());
}
##Update##
That is strange, it doesn't work in different assemblies. Someone can give us the long definition about why the object.equals from different assemblies behaves differently, but for different assemblies, this will work, any variance in the object values will return a different hash code.
Class2Stub.Verify(x => x.ExecuteNonQuery(testString, It.Is<object>(o => o.GetHashCode() == (new { fid = 123, inputStr = "000456" }).GetHashCode())), Times.Once());
One option is to "verify" it in a Callback. Obviously this needs to be done at Setup time, e.g.:
aMock.Setup(x => x.Method(It.IsAny<object>())).Callback<object>(
(p1) =>
{
dynamic o = p1;
Assert.That(o.Name, Is.EqualTo("Bilbo"));
});
None of the answers are great when your test assembly is different than the system under test's assembly (really common). Here's my solution that uses JSON serialization and then strings comparison.
Test Helper Function:
using Newtonsoft.Json;
public static class VerifyHelper
{
public static bool AreEqualObjects(object expected, object actual)
{
var expectedJson = JsonConvert.SerializeObject(expected);
var actualJson = JsonConvert.SerializeObject(actual);
return expectedJson == actualJson;
}
}
Example System Under Test:
public void DoWork(string input)
{
var obj = new { Prop1 = input };
dependency.SomeDependencyFunction(obj);
}
Example Unit Test:
var expectedObject = new { Prop1 = "foo" };
sut.DoWork("foo");
dependency.Verify(x => x.SomeDependencyFunction(It.Is<object>(y => VerifyHelper.AreEqualObjects(expectedObject, y))), Times.Once());
This solution is really simple, and I think makes the unit test easier to understand as opposed to the other answers in this thread. However, because it using simple string comparison, the test's anonymous object has to be set up exactly the same as the system under the test's anonymous object. Ergo, let's say you only cared to verify the value of a single property, but your system under test sets additional properties on the anonymous object, your unit test will need to set all those other properties (and in the same exact order) for the helper function to return true.
I created a reusable method based on Pauls answer:
object ItIsAnonymousObject(object value)
{
return It.Is<object>(o => o.GetHashCode() == value.GetHashCode());
}
...
dependency.Verify(
x => x.SomeDependencyFunction(ItIsAnonymousObject(new { Prop1 = "foo" })),
Times.Once());
Also, this can be used for property name case-insensitive comparison:
protected object ItIsAnonymousObject(object value)
{
var options = new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase };
return It.Is<object>(o => JsonSerializer.Serialize(o, options) == JsonSerializer.Serialize(value, options));
}