如何使用EntityCollection初始化对象?

时间:2017-01-18 16:22:45

标签: c# unit-testing nunit dynamics-crm-2011 moq

我需要我的一个模拟来返回一个特定初始化的对象。我目前的设置是:

_mockOrganizationService.Setup(
        x => x.Retrieve("serviceappointment", It.IsAny<Guid>(), It.IsAny<ColumnSet>()))
    .Returns(new ServiceAppointment());

但是,我不需要返回new ServiceAppointment(),而是需要更多像:

new ServiceAppointment{new EntityCollection("resources")}...

测试中的方法执行:

var sa = serviceAppointment.GetAttributeValue<EntityCollection>("resources");

如何使用EntityCollectionb初始化ServiceAppointment以便我没有得到NullReferenceException?

3 个答案:

答案 0 :(得分:1)

鉴于该服务被定义为

// Instaniate a serviceappointment object
var serviceAppointment = new Entity("serviceappointment");
// Set the attributes you  want for the test
serviceAppointment["resources"] = new EntityCollection();
// Create mock service
var _mockOrganizationService = new Mock<IOrganizationService>();
//Setup retrieval of entity
_mockOrganizationService
    .Setup(x => x.Retrieve(serviceAppointment.LogicalName, It.IsAny<Guid>(), It.IsAny<ColumnSet>()))
    .Returns(serviceAppointment);

var service = _mockOrganizationService.Object;

使用文档中的this example,可以手动定义实体以在测试中使用。

var sa = serviceAppointment.GetAttributeValue<EntityCollection>("resources");

这应该允许被测方法能够调用

sa

前提是使用模拟服务检索CREATE (:Person {forename:'John', surname:'Smith', compNumber:[1,2,3]});

答案 1 :(得分:1)

我将假设您要将填充的对象作为EntityCollection返回。

这是一个示例应用程序,用于填充要在EntityCollection的{​​{1}}字段中使用的PartyList。证据是控制台在执行时会显示2。

Entity

答案 2 :(得分:1)

嘲弄CRM is hard。这就是为什么我写了一个让我的生活更轻松的框架。使用XrmUnitTest,您可以像这样编写测试:

var service = LocalCrmDatabaseOrganziationService.CreateOrganziationService<CrmContext>();
service.Create(new ServiceApointment{
    Resources = new EntityCollection();
});

var serviceAppointment = service.GetFirstOrDefault<ServiceAppointment>();
// serviceAppointment will have a Resources Attribute that is empty.