Tuesday, 2 July 2013

Assert.AreEqual() failing for strings that are equal

Today I almost lost it while doing the simplest of unit tests.

In essence, we had a plugin that would fire on an entity being updated and would set the name of a custom entity to a particular string retrieved from a remote service. The thing was that even though the strings were the same, Assert.AreEqual() was failing.

After many attempts with various StringComparison options, using Trim in a fit of desperation I created a method to check each character in the actual string against the expected string and lo and behold they were different.

The actual string, coming from CRM was using character 160, which is a non-breaking space while the C# code was using character 32, which is a simple space.

The solution was to replace the character 160 with character 32, now the unit tests pass.


const string FirstName="A Random Name";

public void CheckRuleName()
    Entity entity = Service.Retrieve("H2H_rule", RuleId, new Microsoft.Xrm.Sdk.Query.ColumnSet("H2H_name"));
    entity = UpdateEntity(entity, RuleId);
    string result = entity.Attributes["H2H_name"].ToString().Replace((char)160,(char)32);
    Assert.AreEqual(FirstName, result);

No comments:

Post a Comment