我还是嘲笑的新手,我遇到了这段代码的问题:
//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;
到目前为止,我没有遇到过模拟IOrganizationService的问题,但我对execute方法做错了。根据sdk,Execute方法返回一个需要强制转换为正确响应类的OrganizationResponse对象。这是我到目前为止所尝试的:
var idResults = new ParameterCollection();
idResults.Add("Id", Guid.NewGuid());
mockOrganizationService
.Setup(os => os.Execute(It.IsAny<SendEmailFromTemplateRequest>()))
.Returns(new OrganizationResponse
{
Results = idResults,
ResponseName = "SendEmailFromTemplate",
});
当我尝试运行测试时,我不断收到无效的强制转换异常。我想我必须设置错误的响应对象。有人可以向我解释模拟IOrganizationService.Execute方法的正确方法吗?
答案 0 :(得分:6)
您的方法是正确的,但您使用了错误的响应类型。该服务将结果返回为OrganizationResponse
(这是所有响应的基类)。您尝试将基本类型转换为特定类型。这不起作用。
您只需返回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"
});