简体   繁体   English

在CRM 2011插件中模拟IOrganizationService.Execute的问题

[英]Issue with mocking IOrganizationService.Execute in CRM 2011 plugin

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. 到目前为止,我没有遇到过模拟IOrganizationService的问题,但我对execute方法做错了。 According to the sdk the Execute method returns an OrganizationResponse object that needs to be cast into the correct response class. 根据sdk,Execute方法返回一个需要强制转换为正确响应类的OrganizationResponse对象。 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? 有人可以向我解释模拟IOrganizationService.Execute方法的正确方法吗?

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). 该服务将结果作为OrganizationResponse (这是所有响应的基类)返回。 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. 您只需返回SendEmailFromTemplateResponse实例即可使代码正常工作。

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"
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM