带有IStringLocalizer的asp.net核心测试控制器

时间:2017-04-17 22:51:11

标签: c# unit-testing asp.net-core localization xunit

我有本地化的控制器

public class HomeController : Controller
{
    private readonly IStringLocalizer<HomeController> _localizer;

    public HomeController(IStringLocalizer<HomeController> localizer)
    {
        _localizer = localizer;
    }

    [HttpPost]
    public IActionResult SetLanguage(string culture, string returnUrl)
    {
        Response.Cookies.Append(
            CookieRequestCultureProvider.DefaultCookieName,
            CookieRequestCultureProvider.MakeCookieValue(new RequestCulture(culture)),
            new CookieOptions { Expires = DateTimeOffset.UtcNow.AddYears(1) }
        );

        return LocalRedirect(returnUrl);
    }

    public IActionResult Index()
    {
        ViewData["MyTitle"] = _localizer["Hello my dear friend!"];

        return View("Index");
    }
}

我添加了xUnit项目进行测试并编写了下一个代码

public class HomeControllerTest
{
    private readonly IStringLocalizer<HomeController> _localizer;
    private HomeController _controller;
    private ViewResult _result;

    public HomeControllerTest()
    {
        _controller = new HomeController(_localizer);
        _result = _controller.Index() as ViewResult;
    }

    [Fact]
    public void IndexViewDataMessage()
    {
        // Assert
        Assert.Equal("Hello my dear friend!", _result?.ViewData["MyTitle"]);
    }

    [Fact]
    public void IndexViewResultNotNull()
    {
        // Assert
        Assert.NotNull(_result);
    }

    [Fact]
    public void IndexViewNameEqualIndex()
    {
        // Assert
        Assert.Equal("Index", _result?.ViewName);
    }
}

当我运行所有测试时,它们返回false,例外:

  

消息:System.NullReferenceException:未设置对象引用   一个对象的实例。

双击StackTrace光标中的方法时出现在

行上
ViewData["MyTitle"] = _localizer["Hello my dear friend!"];

我认为这是IStringLocalizer所致。怎么解决?可能有人知道是什么原因?

2 个答案:

答案 0 :(得分:9)

设置模拟以返回预期结果。

var mock = new Mock<IStringLocalizer<HomeController>>();
string key = "Hello my dear friend!";
var localizedString = new LocalizedString(key, key);
mock.Setup(_ => _[key]).Returns(localizedString);

_localizer = mock.Object;
_controller = new HomeController(_localizer);

答案 1 :(得分:1)

如果在测试中需要实际本地化资源中的字符串,则可以将 Microsoft.AspNetCore.All Nuget包添加到测试项目中,然后使用以下代码:

var options = Options.Create(new LocalizationOptions {ResourcesPath = "Resources"});
var factory = new ResourceManagerStringLocalizerFactory(options, NullLoggerFactory.Instance);
var localizer = new StringLocalizer<HomeController>(factory);

ResourcesPath应该是从项目根目录中找到HomeController.en.resx的相对路径。