Issue with mocking IOrganizationService.Execute in CRM 2011 plugin

家住魔仙堡 提交于 2019-12-07 15:33:22

问题


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?


回答1:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!