Dynamics CRM 2011 Unit Test Part 8: Microsoft Fakes with IOrganizationService

Dynamics CRM 2011 Unit Test Part 1: Introduction and Series Contents

The complete sample code using Microsoft Fakes can be downloaded from MSDN sample gallery: Dynamics CRM unit test using Microsoft Fakes

Isolate IOrganizationService method call in unit test code should be very simple and straightforward, since it is a well defined interface. With Microsoft Fakes you can use the generated Stub types contained in the generated fake assembly.

Code Under Test


public class OrganizationServiceMethods
 {
 private IOrganizationService _service;

public OrganizationServiceMethods(IOrganizationService service)
 {
 _service = service;
 }

public IEnumerable<Guid> RetrieveAccountIdByName(string name)
 {
 QueryByAttribute query = new QueryByAttribute("account")
 {
 ColumnSet = new ColumnSet("accountid")
 };
 query.Attributes.Add("name");
 query.Values.Add(name);

var result = _service.RetrieveMultiple(query);

List<Guid> ids = new List<Guid>();

foreach (var entity in result.Entities)
 {
 ids.Add(entity.GetAttributeValue<Guid>("accountid"));
 }

return ids;
 }
 }

Unit Test


[TestMethod]
 public void RetrieveAccountIdByNameTest()
 {
 //
 // Arrange
 //
 IEnumerable<Guid> actual;
 IEnumerable<Guid> expected = new List<Guid> { Guid.NewGuid(), Guid.NewGuid() };

int callCount = 0;

var service = new Microsoft.Xrm.Sdk.Fakes.StubIOrganizationService();
 service.RetrieveMultipleQueryBase = (query) =>
 {
 callCount++;

var results = new EntityCollection();

results.Entities.AddRange(
 new Entity("account") { Attributes = { { "accountid", expected.ElementAt(0) } } },
 new Entity("account") { Attributes = { { "accountid", expected.ElementAt(1) } } });

return results;
 };

OrganizationServiceMethods target = new OrganizationServiceMethods(service);

//
 // Act
 //
 actual = target.RetrieveAccountIdByName("TestName");

//
 // Assert
 //
 Assert.AreEqual(callCount, 1); // verify OrganizationServiceContext.RetrieveVersion is called once

Assert.AreEqual(expected.Count(), actual.Count());
 Assert.AreEqual(expected.ElementAt(0), actual.ElementAt(0));
 Assert.AreEqual(expected.ElementAt(1), actual.ElementAt(1));
 }

Advertisements

2 comments on “Dynamics CRM 2011 Unit Test Part 8: Microsoft Fakes with IOrganizationService

  1. Pingback: Dynamics CRM 2011 Unit Test Part 1: Introduction and Series Contents | Zhongchen Zhou's Blog

  2. Pingback: Information to Get started with Unit Testing with Microsoft Fakes and CRM – Hosk's Dynamic CRM Blog

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s