Luc*_*key 1 c# unit-testing localization moq .net-core-2.1
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}"
}
}
Run Code Online (Sandbox Code Playgroud)
这就是我建立测试的方式:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
运行测试将失败并出现以下错误:
SomeMethod() 失败
- Assert.Equal() 失败
- 预计日期: 我的日期: 31.10.2018
- 实际:(空)
通常我会简单地假设该方法GetString(IStringLocalizer, String, Object[])无法处理格式字符串,但由于我在生产环境中使用它并且它有效,所以我不知道如何解决这个问题。对我来说,我似乎已经适当地嘲笑了这种_localizer依赖性。否则将GetString(IStringLocalizer, String)不会返回格式字符串。
为了澄清:
SomeMethod()将失败SomeMethod2()会成功如果您查看GetString扩展方法的代码,只采用字符串的版本确实使用您模拟的方法,但采用额外参数的版本则不会:
return stringLocalizer[name, arguments];
Run Code Online (Sandbox Code Playgroud)
所以你需要嘲笑这个额外的方法IStringLocalizer:
LocalizedString this[string name, params object[] arguments] { get; }
Run Code Online (Sandbox Code Playgroud)
我猜是这样的:
_localizerMock.Setup(lm => lm["key", It.IsAny<object[]>()])
.Returns(new LocalizedString("key", "My Date: {0:d}"));
Run Code Online (Sandbox Code Playgroud)