When unit testing CRM C# codes, you may find that you need to mock the response of calls to CRM’s Organisation service. A number of response classes in the SDK contain an EntityCollection property. This property however is null and is read-only, which means you cannot populate it with mock entries – or at least it seems that way.
This will not work:
var mockResponse = new InstantiateTemplateRequest(); //This won't compile as EntityCollection property does not have a setter mockResponse.EntityCollection = new EntityCollection();
Neither will this:
var mockResponse = new InstantiateTemplateRequest(); //This will give you a run-time exception as EntityCollection property is null. mockResponse.EntityCollection.Add(new Entity());
Behind the scene, the EntityCollection property is actually a facade for reading a key from the Results property. The Results property is defined on the base class of all response classes.
You therefore can set and populate the EntityCollection property as follow:
//The mock response var response = new InstantiateTemplateResponse(); response.Results["EntityCollection"] = new EntityCollection(new List<Entity> { new Entity() }); //response.EntityCollection will now contain one mock entity that we have just configured above.