单元测试时 GetString(IStringLocalizer, String, Object[]) returns null

GetString(IStringLocalizer, String, Object[]) returns null when Unit-Testing

我有一个测试 Class 在某些时候使用 GetString(IStringLocalizer, String, Object[]) 扩展方法

除了测试,下面的都可以使用

public class ClassToTest
{
    private readonly IStringLocalizer<SharedResource> _localizer;
    
    public AnalyticsLogic(IStringLocalizer<SharedResource> localizer)
    {
        _localizer = localizer;
    }
    
    public async Task<string> SomeMethod()
    {
        return _localizer.GetString("key", DateTime.Today));  // "My Date: 31.10.2018" - will return null when testing
    }       

    public async Task<string> SomeMethod2()
    {
        return _localizer.GetString("key");  // "My Date: {0:d}"
    }
}

这就是我建立测试的方式:

public class ClassToTestTest
{
    private readonly ClassToTest _testee;
    private readonly Mock<IStringLocalizer<SharedResource>> _localizerMock = new Mock<IStringLocalizer<SharedResource>>();

    public ClassToTestTest()
    {
        _testee = new ClassToTest(_localizerMock.Object);

        _localizerMock.Setup(lm => lm["key"]).Returns(new LocalizedString("key", "My Date: {0:d}"));
    }



    [Fact]
    public async Task SomeMethod()
    {
        var result = await _testee.SomeMethod();

        Assert.Equal($"My Date: {new DateTime(2018, 10, 31):d}", result);
    }

    [Fact]
    public async Task SomeMethod2()
    {
        var result = await _testee.SomeMethod2();

        Assert.Equal("My Date: {0:d}", result);
    }
}

运行 测试将失败并出现以下错误:

SomeMethod() failed

  • Assert.Equal() Failure
  • Expected: My Date: 31.10.2018
  • Actual: (null)

通常我会简单地假设方法 GetString(IStringLocalizer, String, Object[]) 无法处理格式字符串,但由于我在生产环境中使用它并且它有效,所以我不知道如何解决这个问题。在我看来,我似乎已经正确地嘲笑了 _localizer 依赖项。否则 GetString(IStringLocalizer, String) 不会 return 格式字符串。

编辑:

澄清一下:

如果您查看 GetString 扩展方法的代码,只需要一个字符串的版本 does use the method you have mocked but the version that takes extra parameters doesn't:

return stringLocalizer[name, arguments];

所以你需要嘲笑这个additional method of IStringLocalizer:

LocalizedString this[string name, params object[] arguments] { get; }

我猜是这样的:

_localizerMock.Setup(lm => lm["key", It.IsAny<object[]>()])
    .Returns(new LocalizedString("key", "My Date: {0:d}"));