0

有没有办法在测试中将InstalledUICulture从英语更改为德语?

var groups = new ObservableDictionary<string, IGroupViewModel>(vm => 
    vm.Name.ToString(CultureInfo.InstalledUICulture));
var isGroupExists = groups.ContainsKey(GroupName.ToString(CultureInfo.InstalledUICulture));
if (!isGroupExists)
{
     groups.Add(new GroupViewModel());
}
4

1 回答 1

2

你能给我举个例子吗?

像这样的东西。不要将代码直接耦合到CultureInfo.InstalledUICulture您,而是使用间接层来允许您假装当前的 UI 文化是您想要的任何东西。

我不知道你的类或你如何创建服务,但我假设了某种 DI 并为提供者(或服务或任何你想调用它的东西)使用了构造函数参数

// App code
public interface ICurrentCultureProvider {
    CultureInfo CurrentInstalledUICulture { get; }
}

public class CurrentCultureProvider : ICurrentCultureProvider {
    public CultureInfo CurrentInstalledUICulture => CultureInfo.InstalledUICulture;
}

public class SUT {
    private readonly ICurrentCultureProvider cultureProvider;

    public SUT(ICurrentCultureProvider cultureProvider) {
        this.cultureProvider = cultureProvider;
    }

    public object Method(??? vm) {
        var currentUICulture = cultureProvider.CurrentInstalledUICulture;
        var groups = new ObservableDictionary<string, IGroupViewModel>(vm => vm.Name.ToString(currentUICulture));
        var isGroupExists = groups.ContainsKey(GroupName.ToString(currentUICulture));

        if (!isGroupExists) {
            groups.Add(new GroupViewModel());
        }

        return groups;
    }
}

// Test code. Could make this return any culture by using a parameter.
public class GermanCultureProvider : ICurrentCultureProvider {
    public CultureInfo CurrentInstalledUICulture => new CultureInfo("de-DE");
}

[TestFixture]
public class Sample_Test {

    [Test]
    public void Demo() {
        var sut = new SUT(new GermanCultureProvider());
        var vm = new ???();
        var groups = sut.Method(vm);
        // Assert correct in German etc
    }
}
于 2017-11-10T10:50:51.100 回答