繁体   English   中英

在 TeamCity 中运行 nUnit 测试时错误的 CurrentCulture

[英]Wrong CurrentCulture when running an nUnit test in TeamCity

我有一个依赖于特定文化的单元测试。

在 FixtureSetup 中,我将Thread.CurrentThread.CurrentCultureThread.CurrentThread.CurrentUICulture设置为所需的值 (en-US)。

当我从 Resharper 运行测试时,它通过了。

当我从 TeamCity 运行测试(使用运行程序“NUnit 2.4.6”)时,测试失败,因为CurrentCulturecs-CZ (我的操作系统的文化)。 然而CurrentUICulture仍然是en-US

您可以强制使用特定的文化在当前线程System.Threading.Thread.CurrentThread运行您的测试

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

您还可以使用CultureInfo.GetCultureInfo来提供您想要使用的文化。 这可能是倒在SetUp你的测试的一部分。

请记住将文化恢复到TearDown的前一个文化以确保隔离

[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;
  }
}

似乎 TeamCity 正在不同的线程中运行 FixtureSetup 和单元测试,或者以某种方式修改CurrentUICulture

SetUp (而不是FixtureSetup )中同时设置CurrentUICultureCurrentCulture解决了这个问题。

从 NUnit 2.4.2 开始,您可以使用 SetCulture 属性。

namespace NUnit.Tests
{
  using System;
  using NUnit.Framework;

  [TestFixture]
  [SetCulture("fr-FR")]
  public class FrenchCultureTests
  {
    // ...
  }
}

该示例取自以下链接。 另请参阅链接了解更多详情。

https://github.com/nunit/docs/wiki/SetCulture-Attribute

在我的测试中,我在单个测试方法中设置并重置了 CurrentUICulture

            var tempCurrentUICulture = Thread.CurrentThread.CurrentUICulture;
            try
            {
                Thread.CurrentThread.CurrentUICulture = new CultureInfo("zh-HK" );
                 actual = target.MethodToTest(resourceSet, localeId);
            }
            finally
            {
                Thread.CurrentThread.CurrentUICulture = tempCurrentUICulture;
            }

我有类似的问题。 TeamCity 以某种方式忽略了我即时传递的 CultureInfo 实例。 近 15 年来,相同的测试和方法在所有其他平台和运行器(resharper、mstest、ncrunch 等)上都按预期运行。 我的案例不是关于管理文化背景(UICulture、Thread、SetCulture 等)。 它一定是搞乱了 .NET 框架配置或其他东西。 令人困惑。

[Test]
public void WhatIsGoingOnWithTheCulture()
{
     //This method should pass. It should return "İ", it is Turkish letter.
     Assert.AreEqual("İ","i".ToUpper(new CultureInfo("tr-TR")));
}

//String lengths are both 1. Strings differ at index 0.
//  Expected: "Ý"
//  But was:  "İ"

TeamCity:2020.2(内部版本 85487),使用 Nunit3 和 NUnitConsole 3.11.1 进行测试

.Net 框架 4.8

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM