When I was writing the Unit test I got stuck at one point where I saw the code which will create 1:N relationships. But the problem was how to achieve that code in the unit test method? I searched everywhere but did not get a proper solution.
So in this blog, I am going to explain how to write a method for "EntityMetadata: OneToManyRelationshipMetadata".
SDK Reference
- using Microsoft.Xrm.Sdk.Metadata;
Plugin code
- RetrieveEntityRequest request = new RetrieveEntityRequest()
- {
-
-
-
- EntityFilters = EntityFilters.Relationships,
- LogicalName = "account",
- RetrieveAsIfPublished = false,
- };
-
- RetrieveEntityResponse response = (RetrieveEntityResponse)service.Execute(request);
- if (response.EntityMetadata != null)
- {
- foreach (var relationships in response.EntityMetadata.OneToManyRelationships)
- {
- if (relationships.IsCustomizable.Value)
- {
- var referencingEntity = relationship.ReferencingEntity;
- var referencingAttribute = relationship.ReferencingAttribute;
-
-
-
- }
- }
- }
Based on the above plugin code we will write the unit test method,
- [TestMethod]
- public void EntityMetadataMethod()
- {
- OrganizationService.ExecuteOrganizationRequest = (request) =>
- {
-
-
-
- BooleanManagedProperty property = new BooleanManagedProperty()
- {
- Value = true
- };
-
-
-
- OneToManyRelationshipMetadata[] OneToManyRelationships = new OneToManyRelationshipMetadata[]
- {
- new OneToManyRelationshipMetadata()
- {
- ReferencingEntity = "account",
- ReferencingAttribute = "primarycontactid",
- IsCustomizable = property,
- SchemaName = "new_account_contact"
- },
- new OneToManyRelationshipMetadata()
- {
- ReferencingEntity = "contact",
- ReferencingAttribute = "parentaccountid",
- IsCustomizable = property,
- SchemaName = "new_contact_account"
- }
- };
-
-
-
- EntityMetadata metadata = new EntityMetadata()
- {
- SchemaName = "salesorder"
- };
-
- metadata.GetType().GetProperty("OneToManyRelationships").SetValue(metadata, OneToManyRelationships);
- OrganizationResponse responce = new RetrieveEntityResponse();
- responce["EntityMetadata"] = metadata;
- return responce;
- };
- }
Using the above unit test method code we can achieve our code coverage. If you want to learn how to write unit test code with different data types and different methods please read my blog on the Unit test -
Unit test using fakes.
I hope the above solution will help with your code coverage.
Keep learning new things....!!