SetCulture
SetCultureAttribute is used to set the current CultureInfo.CurrentCulture for the duration of a test. The culture remains set until the test or fixture completes and is then reset to its original value.
This attribute affects formatting operations such as number formatting, date formatting, and string comparisons that depend on culture settings.
Constructor
SetCultureAttribute(string culture)
| Parameter | Type | Description |
|---|---|---|
culture |
string |
The name of the culture to use (e.g., "fr-FR", "de-DE", "en-US"). Must be a valid culture name recognized by CultureInfo. |
Applies To
| Test Methods | Test Fixtures (Classes) | Assembly |
|---|---|---|
| ✅ | ✅ | ✅ |
Note
If SetCultureAttribute is applied at fixture or assembly level, the culture setting applies to all contained tests.
When applied at multiple levels, the most specific level takes precedence. The attribute is inherited by derived test fixtures.
Examples
Setting Culture on a Fixture
[TestFixture]
[SetCulture("fr-FR")]
public class FrenchCultureTests
{
[Test]
public void TestDateFormatting()
{
// This test runs with French culture
var date = new DateTime(2024, 12, 25);
string formatted = date.ToString("d");
// French date format: dd/MM/yyyy
Assert.That(CultureInfo.CurrentCulture.Name, Is.EqualTo("fr-FR"));
}
[Test]
public void TestNumberFormatting()
{
// French uses comma as decimal separator
double value = 1234.56;
string formatted = value.ToString("N2");
Assert.That(formatted, Does.Contain(","));
}
}
Setting Culture on Individual Methods
[TestFixture]
public class MixedCultureTests
{
[Test]
[SetCulture("de-DE")]
public void TestWithGermanCulture()
{
// Only this test runs with German culture
Assert.That(CultureInfo.CurrentCulture.Name, Is.EqualTo("de-DE"));
}
[Test]
[SetCulture("ja-JP")]
public void TestWithJapaneseCulture()
{
// Only this test runs with Japanese culture
Assert.That(CultureInfo.CurrentCulture.Name, Is.EqualTo("ja-JP"));
}
[Test]
public void TestWithDefaultCulture()
{
// This test runs with the system's default culture
Assert.That(CultureInfo.CurrentCulture, Is.Not.Null);
}
}
Combining with SetUICulture
[TestFixture]
public class CombinedCultureTests
{
[Test]
[SetCulture("fr-FR")]
[SetUICulture("de-DE")]
public void TestWithDifferentCultures()
{
// Culture affects formatting (numbers, dates)
Assert.That(CultureInfo.CurrentCulture.Name, Is.EqualTo("fr-FR"));
// UICulture affects resource loading (UI strings)
Assert.That(CultureInfo.CurrentUICulture.Name, Is.EqualTo("de-DE"));
}
}
Notes
- Only one culture may be specified per attribute. To test with multiple cultures, create separate test methods or use parameterized tests.
SetCultureaffectsCultureInfo.CurrentCulture, which controls formatting operations. UseSetUICultureto controlCultureInfo.CurrentUICulturefor resource loading.- If you need to conditionally run tests based on the current culture (rather than setting it), use the
Cultureattribute instead.