FakeXRMEasy:使用AddFakeMessageExecutor覆盖更新请求的行为

时间:2019-04-04 21:13:00

标签: c# dynamics-crm microsoft-dynamics dynamics-365 fakexrmeasy

我正在尝试为Update请求引发异常的情况创建测试。使用FakeXRMEasy可以做到吗?我已经尝试过使用AddFakeMessageExecutor,但目前无法正常工作:

我的虚假消息执行程序类:

public class UpdateExecutor : IFakeMessageExecutor
{
    public bool CanExecute(OrganizationRequest request)
    {
        return request is UpdateRequest;
    }

    public OrganizationResponse Execute(
        OrganizationRequest request,
        XrmFakedContext ctx)
    {
        throw new Exception();
    }

    public Type GetResponsibleRequestType()
    {
        return typeof(UpdateRequest);
    }
}

用于测试:

fakeContext.Initialize(new Entity[] { agreement });
fakeContext.AddFakeMessageExecutor<UpdateRequest>(new UpdateExecutor());

fakeContext.ExecuteCodeActivity<AgreementConfirmationWorkflow>(fakeContext.GetDefaultWorkflowContext());

在工作流程中,更新请求称为:

var workflowContext = executionContext.GetExtension<IWorkflowContext>();
var serviceFactory = executionContext.GetExtension<IOrganizationServiceFactory>();
IOrganizationService service = serviceFactory.CreateOrganizationService(workflowContext.UserId);

/// some code to retrieve entity and change attributes ///

service.Update(entity);

我希望这引发异常,但此刻更新请求已成功完成。我该如何工作?

1 个答案:

答案 0 :(得分:1)

IFakeMessageExecutor仅在您调用IOrganizationService.Execute方法时有效。因此,如果您更改service.Update(entity);的{​​{1}}代码行,它应该可以工作。

这里是一个完整的工作示例供参考:

CodeActivity

service.Execute(new UpdateRequest { Target = entity});

FakeMessageExecutor实例

    public class RandomCodeActivity : CodeActivity
    {
        protected override void Execute(CodeActivityContext context)
        {
            var workflowContext = context.GetExtension<IWorkflowContext>();
            var serviceFactory = context.GetExtension<IOrganizationServiceFactory>();
            var service = serviceFactory.CreateOrganizationService(workflowContext.UserId);

            var accountToUpdate = new Account() { Id = new Guid("e7efd527-fd12-48d2-9eae-875a61316639"), Name = "A new faked name!" };

            service.Execute(new UpdateRequest { Target = accountToUpdate });
        }
    }

测试(使用xUnit测试库)

    public class FakeUpdateRequestExecutor : IFakeMessageExecutor
    {
        public bool CanExecute(OrganizationRequest request)
        {
            return request is UpdateRequest;
        }

        public OrganizationResponse Execute(OrganizationRequest request, XrmFakedContext ctx)
        {
            throw new InvalidPluginExecutionException("Throwing an Invalid Plugin Execution Exception for test purposes");
        }

        public Type GetResponsibleRequestType()
        {
            return typeof(UpdateRequest);
        }
    }