I am still new to mocking and I am having trouble with this code:
//create the request
SendEmailFromTemplateRequest emailUsingTemplateReq =
new SendEmailFromTemplateRequest
{
Target = email,
TemplateId = new Guid("07B94C1D-C85F-492F-B120-F0A743C540E6"),
RegardingId = toParty[0].PartyId.Id,
RegardingType = toParty[0].PartyId.LogicalName
};
//retrieve response
SendEmailFromTemplateResponse emailUsingTemplateResponse =
(SendEmailFromTemplateResponse)service.Execute(emailUsingTemplateReq);
var emailId = emailUsingTemplateResponse.Id;
I have had no problems up to this point mocking the IOrganizationService, but I am doing something wrong with the execute method. According to the sdk the Execute method returns an OrganizationResponse object that needs to be cast into the correct response class. Here is what I have tried so far:
var idResults = new ParameterCollection();
idResults.Add("Id", Guid.NewGuid());
mockOrganizationService
.Setup(os => os.Execute(It.IsAny<SendEmailFromTemplateRequest>()))
.Returns(new OrganizationResponse
{
Results = idResults,
ResponseName = "SendEmailFromTemplate",
});
When I try to run the test I keep getting an invalid cast exception. I figure I must be setting up the response object wrong. Can someone explain to me the correct way to mock the IOrganizationService.Execute method?
Your approach is correct, but you use the wrong response type. The service returns the results as OrganizationResponse
(which is the base class for all responses). You try to cast the base type into a specific type. This doesn't work.
You simply have to return an instance of SendEmailFromTemplateResponse
to get your code working.
var orgService = new Mock<IOrganizationService>();
var idResults = new ParameterCollection
{
{"Id", Guid.NewGuid()}
};
orgService.Setup(s => s.Execute(It.IsAny<SendEmailFromTemplateRequest>()))
.Returns(new SendEmailFromTemplateResponse
{
Results = idResults,
ResponseName = "SendEmailFromTemplate"
});
来源:https://stackoverflow.com/questions/6903128/issue-with-mocking-iorganizationservice-execute-in-crm-2011-plugin