Actual and expected values ​​in NUnit test for decimal extension format do not match

I wrote the following extension method:

public static class DecimalExtensions
{
   public static string FormatCurrency(this decimal instance)
   {
      return string.Format("{0:c}", instance);
   }
}

NUnit test:

[TestFixture]
public class DecimalExtensionsTests
{
   [Test]
   public void Format_should_return_formatted_decimal_string()
   {
      // Arrange
      decimal amount = 1000;

      // Act
      string actual = amount.FormatCurrency();

      // Assert
      Assert.AreEqual("R 1 000,00", actual);
   }
}

My test fails, and I'm not sure why. The error I am getting is the following:

String lengths are both 10. Strings differ at index 3.
  Expected: "R 1 000,00"
  But was:  "R 1 000,00"
  --------------^
+5
source share
1 answer

Your problem really arises from the presentation of space in digital format. The space in which you are experiencing problems is defined in NumberFormatInfoclass' CurrencyGroupSeparator. If you check the character codes of both the standard ASCII space and the section separator of a currency group with the following fragment

Console.WriteLine("Space code: {0}", (Int32)' ');
var separator = Thread.CurrentThread.CurrentCulture.NumberFormat
    .CurrencyGroupSeparator;
Console.WriteLine("Currency separator code: {0}", (Int32)separator[0]);

... , 32 160 . .

ASCII, :

Thread.CurrentThread.CurrentCulture.NumberFormat.CurrencyGroupSeparator = " ";

. , , unit test. , , . ( ), , :

public static string FormatCurrency(this decimal instance)
{
   return instance.FormatCurrency(Thread.CurrentThread.CultureInfo);
}

public static string FormatCurrency(this decimal instance, CultureInfo culture)
{
    return string.Format(culture, "{0:c}", instance);
}

unit test , (, , ):

[Test]
public void FormatCurrency_should_return_formatted_decimal_string()
{
    decimal amount = 1000;
    var culture = CultureInfo.CreateSpecificCulture("en-us");
    // replacing space (160) with space (32)
    culture.NumberFormat.CurrencyGroupSeparator = " ";

    // Act
    string actual = amount.FormatCurrency(culture);

    // Assert
    Assert.AreEqual("$1 000.00", actual);
}

.

+4

All Articles