我有一个测试类,该类有时会使用
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()失败
- Assert.Equal()失败
- 预计:我的约会日期:2018年10月31日
- 实际:(空)
通常,我只是假设方法GetString(IStringLocalizer, String, Object[])
不能处理格式字符串,但是由于im在生产环境中使用了它并且可以正常工作,因此我不知道如何解决此问题。在我看来,我似乎已经适当地嘲笑了_localizer
依赖项。否则GetString(IStringLocalizer, String)
将不会返回格式字符串。
为澄清起见:
SomeMethod()
将失败SomeMethod2()
将成功答案 0 :(得分:3)
如果您查看GetString
扩展方法的代码,则该版本仅包含字符串does use the method you have mocked,而该版本仅包含字符串takes extra parameters doesn't:
return stringLocalizer[name, arguments];
因此您需要嘲笑additional method中的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}"));