Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wrong CurrentCulture when running an nUnit test in TeamCity

I have a unit-test that relies on a specific culture.

In FixtureSetup, I set both Thread.CurrentThread.CurrentCulture and Thread.CurrentThread.CurrentUICulture to the desired value (en-US).

When I run the test from Resharper, it passes.

When I run the test from TeamCity (using the runner "NUnit 2.4.6"), the test fails, because CurrentCulture is cs-CZ (the culture of my OS). However CurrentUICulture is still en-US.

like image 761
Miroslav Bajtoš Avatar asked Jan 19 '11 07:01

Miroslav Bajtoš


People also ask

How does NUnit decide what order to run tests in?

Ordered tests are started in ascending order of the order argument. Among tests with the same order value or without the attribute, execution order is indeterminate.

What is used to run the NUnit Test cases?

Most of the . NET developers use Visual Studio for writing code as it eases the process of test case development, debugging, testing, and maintenance. NUnit Visual Studio Adapter is used to execute NUnit tests as it works with all the current editions of Visual Studio.

What is Testmethod in NUnit?

The Test attribute is one way of marking a method inside a TestFixture class as a test. For backwards compatibility with previous versions of Nunit a test method may also be found if the first 4 letters are "test" regardless of case.

What is NUnit Test Project C#?

NUnit is a unit-testing framework for all . Net languages. NUnit is Open Source software and NUnit 3.0 is released under the MIT license. This framework is very easy to work with and has user friendly attributes for working.


2 Answers

You can force a specific culture for running your tests in your current thread System.Threading.Thread.CurrentThread

// set CurrentCulture to Invariant
Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
// set UI culture to invariant
Thread.CurrentThread.CurrentUICulture = CultureInfo.InvariantCulture;

You can also use CultureInfo.GetCultureInfo to provide the culture you want to use. This can be down in the SetUp part of your tests.

Remember to restore the culture to the previous one in your TearDown to ensure isolation

[TestFixture]
class MyTest {
  CultureInfo savedCulture;

  [SetUp]
  public void SetUp() {
    savedCulture = Thread.CurrentThread.CurrentCulture;
    Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
  }

  [TearDown]
  public void TearDown() {
    Thread.CurrentThread.CurrentCulture = savedCulture;
  }
}
like image 121
Nekresh Avatar answered Nov 15 '22 01:11

Nekresh


It seems like TeamCity is running FixtureSetup and unit-test in different threads, or somehow modifying CurrentUICulture.

Setting both CurrentUICulture and CurrentCulture in SetUp (instead of FixtureSetup) solved the problem.

like image 33
Miroslav Bajtoš Avatar answered Nov 15 '22 01:11

Miroslav Bajtoš